Skip to content

Commit

Permalink
Merge pull request #167 from glihm/docs/add-model-info
Browse files Browse the repository at this point in the history
docs: add models info
  • Loading branch information
gianalarcon authored Dec 21, 2023
2 parents 7c299d3 + 31a5aec commit 2ff5506
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/cairo/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ Here we are retrieving the `Position` and `Moves` models from the world state. W

You can then use `position` and `moves` as you would as any other Cairo struct.

In the case that your model defines several keys as the [resource example](./models.md#the-key-attribute), you must provide a value for each key.

```rust,ignore
let player = get_caller_address();
let location = 0x1234;
let resource = get!(world, (player, location), (Resource));
```

If you use the `get!` command on a model that has never been set before, all the fields that are not `#[key]` are equal to 0 in the returned model, which is the default value in the storage.

### The `set!` command

The `set!` command is used to update models state.
Expand Down
13 changes: 12 additions & 1 deletion src/cairo/models.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ struct Moves {

#### The #[key] attribute

The `#[key]` attribute indicates to Dojo that this model is indexed by the `player` field. You need to define a key for each model, as this is how you query the model. However, you can create composite keys by defining multiple fields as keys.
The `#[key]` attribute indicates to Dojo that this model is indexed by the `player` field. A field that is identified as a `#[key]` is not stored. It is used by the dojo database system to uniquely identify the storage location that contains your model.

You need to define at least one key for each model, as this is how you query the model. However, you can create composite keys by defining multiple fields as keys. If you define multiple keys, they must **all** be provided to query the model.

```rust,ignore
#[derive(Model, Copy, Drop, Serde)]
Expand Down Expand Up @@ -56,6 +58,15 @@ set!(
);
```

To retrieve a model with a composite key using the [get!](./commands.md#the-get-command) command, you must provide a value for each key as follow:

```rust,ignore
let player = get_caller_address();
let location = 0x1234;
let resource = get!(world, (player, location), (Resource));
```

#### Implementing Traits

Models can implement traits. This is useful for defining common functionality across models. For example, you may want to define a `Position` model that implements a `PositionTrait` trait. This trait could define functions such as `is_zero` and `is_equal` which could be used when accessing the model.
Expand Down

0 comments on commit 2ff5506

Please sign in to comment.