Yes, this is enough (except that you inserted Order
class name instead), however it's also recommended to add PHPDoc for relations:
User
model:
/**
* ...
*
* @property Post[] $posts
*/
class User
{
/**
* @return \yii\db\ActiveQuery
*/
public function getPosts()
{
return $this->hasMany(Post::className(), ['user_id' => 'id']);
}
}
Post
model:
/**
* ...
*
* @property User $user
*/
class Post
{
/**
* @return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
}
Then when you will call $user->posts
or $post->user
you will get full autocomplete if you are using IDE. It's also useful because you can see the relation list just by looking at the top of the file, because relations accessed as virtual properties, $user->getPosts()
call will return yii\db\ActiveQuery
object and not \yii\db\ActiveRecord
array. It's better to separate them with linebreak from model attributes (they are also added for autocomplete and seeing the structure of according database table without looking at database).
By the way, if you generate model with Gii, if you specified foreign keys correctly, relations and PHPDoc will be generated automatically.
Note that if you don't need to use $post->user
, you can omit user
relation declaration in Post
model. You can declare relations that are only needed for usage.