Task. It is necessary to select all the data from the posts table and to this data attach the name field from the categories table (where post.category-id = categories.id), which indicates the category the publication belongs to. How to do it with active record?

    1 answer 1

    Actually the model itself

    class Post extend ActiveRecord { //Релейшен на категорию public function getCategory(){ return $this->hasOne(Category::className(), ['id' => 'category-id']); } } //Такой пост существует if($model = Post::findOne(1)){ //У этого поста есть категория if($category = $model->category){ //Получаем имя категории echo category->name; } } 
    • not. in this case, I will receive two objects and will not be able to sort through all the data in one cycle - Sergey O
    • one
      C what kind of happiness will you have two objects? Objects you will have as many posts as you pull out of the database. In this case, findOne hints as if the object is one - Ninazu
    • Everything. I understood how it works, thanks. - Sergey About