简体   繁体   English

无法使用联接从多个表中获取记录

[英]unable to fetch records from multiple tables using join

I am using Yii framework. 我正在使用Yii框架。 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 我的模型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 模型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. 让Yii担心加入您的桌子。 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. -> with()用于急切加载,因此此时您可能不需要它。 In fact, unless I misread you completely, you can remove your criteria all together. 实际上,除非我完全误解了您,否则您可以一起删除所有条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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