简体   繁体   中英

unable to fetch records from multiple tables using join

I am using Yii framework. i am wonder how i can get records from multiple tables i did research but couldn't find any usefull link i am using following code for this please let me know where i am missing

my model Task.php

public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'prj_user' => array(self::BELONGS_TO, 'User', 'id'),
    );
}

model User.php

public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        array('task', self::HAS_MANY, 'Task','project_id')
    );
}

and this is my main controller

$criteria = new CDbCriteria;
$criteria->compare('t.id', 1);
$criteria->with = array( 'prj_user' => array('select' => 'username,title,roles', 'joinType'=>'inner join'));

$rows = Task::model()->findAll( $criteria );

but still i am getting columns only from task table but i need more three columns from users table please help me

Let Yii worry about joining your tables. Your relations looks fine so you should be able to access them directly

For example, what does this return?

foreach ($rows as $task)
{
    if ( isset($task->prj_user) )
        echo $task->prj_user->username . "<br>";
}

Or this?

this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>new CActiveDataProvider('Task'),
    'columns'=>array(
        'id',
        'prj_user.username',
        'prj_user.title',
        'prj_user.roles',
    )
));

->with() is used for eager loading, so at this point you probably don't need it. In fact, unless I misread you completely, you can remove your criteria all together.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM