public function relations() { return array( 'idAuthor' => array(self::BELONGS_TO, 'User', 'id'), ); } public function relations() { return array( 'articles' => array(self::HAS_MANY, 'Article', 'id_author'), ); } $post= Article::model()->findByPk(1); echo $post->title; echo $post->login; 

Article1 table: title, content, id_author. table2 User: id, login.

where is the mistake? Property "Article.login" is not defined. how to fix?

    2 answers 2

    I do not remember exactly. So I can be wrong. But most likely you need to also indicate what kind of connection you use.

    That is something like this:

     $post= Article::model()->findByPk(1); echo $post->articles->title; echo $post->idAuthor->login; 
    • This is exactly what is needed through -> and communication instructions :) answer +1 - Artem
    • correction: $acticle = Article::model()->findByPk(1); $acticle->title; // название статьи $acticle->idAuthor->login // имя автора $acticle = Article::model()->findByPk(1); $acticle->title; // название статьи $acticle->idAuthor->login // имя автора $acticle = Article::model()->findByPk(1); $acticle->title; // название статьи $acticle->idAuthor->login // имя автора - VasyOk

    So you can conveniently specify the search:

     $post = Article::model()->with('idAuthor')->findByPk(1); 

    Returns the Article entry with the User related User entry.

    Then:

     $post->idAuthor->login. 

    Like so.

    I did not immediately understand the answer above. A small personal question: is it possible to access a record by communication without calling the with('имя\_связи') method with('имя\_связи') ?

    • 2
      can. with with() a request is generated for one common request with JOINs, and without - an additional request is created. Therefore, without with() loading is lazy, i.e. get data when you need it, not immediately. Personally, in my opinion, the simpler the request, the faster the response. Therefore, I use with with() in rare cases. - VasyOk
    • @VasyOk, thank you for a very reasoned answer) - Ray