Hello everyone, help please, I have 2 tables

tb_users { id username password email } tb_coupon { id user_id } 

I need to have user_id from tb_coupon get user login, I wrote a relational query in Coupon model

 public function relations() { return array( 'user'=>array(self::BELONGS_TO, 'Users', 'username'), ); } 

But when I address this

 $profile = Coupon::model()->findByPk(36); echo $profile->user; 

I get an error

 Не определено свойство "Coupon.username". 

Did on off. documentation, please help me, what did I do wrong?

  <?php $dataProvider = new CActiveDataProvider('Coupon'); $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$dataProvider, 'summaryText'=>false, 'columns'=>array( 'place'=>array( 'name'=>'place', 'value'=>'$row + 1', 'header'=>'Место', ), 'username'=>array( 'name'=>'username', 'value'=>'Coupon::model()->user', 'header'=>'Логин', ), ), )); ?> 

    2 answers 2

    in general, as far as I remember, in order to pull out the subtables with the request, so write it down

     $profile = Coupon::model()->with('user')->findByPk(36); 

    with ('user') - indicates with which links we load data

    data is output like this

     $profile->getRelated("user")->username 
    • I executed the code, there is no error, but nothing is output, when I try to make echo $ profile-> username; There is an error that Coupon.username was not found, tell me how to display information - Angus123
    • Needed: echo $ profile-> user-> username; - KiTE
    • Thank you very much, did not know, now I know :) - Angus123

    It is necessary so:

     'user' => array(self::BELONGS_TO, 'Users', 'user_id'), 
    • Thanks for the answer, I made a small mistake in the question, I wrote a relational query not in the Users model, but in Coupon, and now it does not produce errors, but it does not output data either. PS Updated the first post, indicated the widget code. - Angus123