From 31a5aecdb59cd90907fc081eac835ed2f6f9af76 Mon Sep 17 00:00:00 2001 From: glihm Date: Wed, 20 Dec 2023 20:02:11 -0600 Subject: [PATCH] docs: add models info --- src/cairo/commands.md | 11 +++++++++++ src/cairo/models.md | 13 ++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/cairo/commands.md b/src/cairo/commands.md index 3aba5f9a..0b76359d 100644 --- a/src/cairo/commands.md +++ b/src/cairo/commands.md @@ -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. diff --git a/src/cairo/models.md b/src/cairo/models.md index a16092ed..e1a22c93 100644 --- a/src/cairo/models.md +++ b/src/cairo/models.md @@ -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)] @@ -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.