我对这个Yii CGridView问题感到沮丧,任何帮助或指导都将不胜感激。
我有两个相关的表shops (shop_id primary)和contacts (shop_id foreign),这样一个商店就可以有多个联系人。我使用CGridview来拉取记录和排序,我在商店模型中的关系函数类似于:
'shopscontact' => array(self::HAS_MANY, 'Shopsmodel', 'shop_id');
在商店网格上,我需要显示具有任何一个可用联系人的商店行。我的过滤,搜索网格的尝试运行得很好,但我陷入了一个非常奇怪的问题。相应的网格列不显示所需的值。
在CGridview文件中,我正在做类似这样的事情
array(
'name' => 'shopscontact.contact_firstname',
'header' => 'First Name',
'value' => '$data->shopscontact->contact_firstname'
),
要显示联系人的名字,请执行以下操作。但是,即使在搜索/排序都有效的情况下(我是通过检查数据库关联发现的),网格列也是空的!:(当我执行var_dump时
array(
'name' => 'shopscontact.contact_firstname',
'header' => 'First Name',
'value' => 'var_dump($data->shopscontact)'
),
转储显示_private属性中的记录值,如下所示:
private '_attributes' (CActiveRecord) =>
array
'contact_firstname' => string 'rec1' (length=4)
'contact_lastname' => string 'rec1 lsname' (length=11)
'contact_id' => string '1' (length=1)
<编辑:>
我在模型中的标准代码如下:
$criteria->with = array(
'owner',
'states',
'shopscontacts' => array(
'alias' => 'shopscontacts',
'select' => 'shopscontacts.contact_firstname,shopscontacts.contact_lastname',
'together' => true
)
);
如何访问各自列中的值?请帮帮忙!:
发布于 2012-01-15 04:13:51
嗯,我并没有经常使用with()和the ()方法。有趣的是,在列的“值”部分,$data->shopscontacts
如何根据relations()
定义(而不是基于您声明的criteria
)加载关系。
处理数组输出的一种更简洁的方法可能如下所示:
'value' => 'array_shift($data->shopscontacts)->contact_lastname'
也许做这个更好的方法是在你的shops
模型中建立一个新的(额外的)关系,就像这样:
public function relations()
{
return array(
'shopscontacts' => array(self::HAS_MANY, 'Shopsmodel', 'shop_id'), // original
'firstShopscontact' => array(self::HAS_ONE, 'Shopsmodel', 'shop_id'), // the new relation
);
}
然后,在您的CGridView中,您可以像这样设置一个列:
'columns'=>array(
'firstShopscontact.contact_lastname',
),
干杯
发布于 2012-01-14 06:40:03
因为'shopscontact‘是多个关系的名称,所以$data->shopscontact
应该返回一个包含所有相关商店的数组……您是否修改了关系以便只返回一条记录(如果我没有弄错,您只需要显示一条记录,对吗?)?如果是你做的,我可以看看你的过滤代码吗?
附言:你有没有尝试过'value' => '$data->shopscontact['contact_firstname']'
?
https://stackoverflow.com/questions/8857314
复制相似问题