4

Let's say we have two entities: User and Post.

In my understanding, in order to have a one-to-many relationship between User and Post, you need to do the following:

class User {

...

    public function getPosts()
    {
        return $this->hasMany(Order::className(), ['user_id' => 'id']);
    }

}

class Post {

...

    public function getUser()
    {
        return $this->hasOne(Order::className(), ['id' => 'user_id']);
    }

}

Is this right? Is there anything else I need to add in order to make everything work? The Yii2 documentation is not very clear to me.

jarvan
  • 449
  • 3
  • 9
  • 25
  • Be more concrete please. What dosen't works? or What are you trying to do?, the code seem correct, if you want to do relations with Order model, but I suppose that you want to do them between Post and User class, is this correct? – Tino Fernández Jan 12 '16 at 23:52

1 Answers1

10

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.

arogachev
  • 33,150
  • 7
  • 114
  • 117