YII2 model association one-to-many

Demand, a user has multiple articles to query all

Article table

 user table

 

 

 

 

 

// First find out a user 
        $user=Users::find()-> where ([ ' id ' => ' 41 ' ])-> one();

        // The first parameter is still the associated model, the second is still an array, the first of the array is the foreign key of the associated model, and the second is its own foreign key 
        $info= $user->hasMany(Post:: className(),[ " user_id " => " id " ])->asArray()-> all();

        var_dump ($ info);

 

written in the model

public function getPosts()
    {
         return  $this->hasMany(Post::className(),["user_id"=>"id"])->asArray();

    }

 

  var_dump($user->posts);

 

 

 

 

OK!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325173806&siteId=291194637