开发者

Yii relations trouble when trying to display CGridView from 2 models

开发者 https://www.devze.com 2023-04-09 05:13 出处:网络
Image describing the tables -> http://i.stack.imgur.com/ki开发者_运维技巧2YP.jpg Each of the tables is a model.

Image describing the tables -> http://i.stack.imgur.com/ki开发者_运维技巧2YP.jpg

Each of the tables is a model.

Main model which shows through CGridView is "RegularTask".

Now I need it to display fields from "YearlyTask" in the same row.

"hp_id" and "up_id" are FK (foreign keys) in both tables.

I tried to set the relations() in the RegularTask model like this:

'arp' => array(self::BELONGS_TO, 'YearlyTask', 'hp_id, up_id'),

Then I try to display the "is_sent" and "is_reported" fields from YearlyTask by using "arp.is_sent" and "arp.is_reported", but nothing shows up (not even error). While data from RegularTask displays normally.

What am I doing wrong?

Here is a snippet from the dataprovider..

<?php
$dataProvider=new CActiveDataProvider('RegularTask', array(
    'criteria'=>array(
        'condition'=>'t.id_id=' . $model->id,
        'order'=>'t.created DESC',
        'with'=>array('arp'),
    ),
    'pagination'=>array(
        'pageSize'=>10,
    ),
));

$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'columns'=>array(
        'comment',
        'arp.is_sent'
    ),
));
?>


Foreign key in one table must be primary key in linked table. If you look into SQL statement created by Yii with your structure, you will see something like this (simplified):

SELECT `t`.*, `arp`.* FROM `RegularTask` `t` LEFT OUTER JOIN `YearlyTask` `arp` ON (`t`.`hp_id`=`arp`.`id`) AND (`t`.`up_id`=`arp`.`id`)

As you can see, what it looks for is that both RegularTask.hp_id and RegularTask.up_id have same value as YearlyTask.id which isn't correct. You have several solutions. One of them is create new column in RegularTask like yt_id which will be foreign key for YearlyTask.id and in my opinion it's the best solution.

Otherwise you can delete your primary key column id in RegularTask table and make hp_id and up_id as complex primary key. In this case you can use the way you tried before, but as i don't know your full db structure i can't guarantee that it's good solution.


have you tried using this style:

$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'columns'=>array(
        'comment',
        array(
            'header'=>'Sent',
            'type'=>'raw',
            'value'=>'$data->arp->is_sent',
        )
    ),
));

perhaps not the most elegant way, but might be of help

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号