本文介绍了yii - 使用关系 HAS_ONE 从相关表中获取数据以显示在列表页面中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两张桌子

大(id,bigs_name,smallid),

big (id, bigs_name, smallid),

small(id, smallguys_name)

small(id, smallguys_name)

因此有两个模型 - 大和小

therefore two models - big and small

我在大模型中使用了以下关系,(我希望这个关系是正确的)

i have used the following relation in the big model, (I hope this relation is correct)

'has_small'  => array(self::HAS_ONE, 'small', 'smallid')

默认情况下,actionIndex 被创建为

by default the actionIndex was created as

public function actionIndex()
{
  $dataProvider=new CActiveDataProvider('IphoneSubscription');
  $this->render('index',array(
   'dataProvider'=>$dataProvider,
  ));
}

在 _view.php 中,我想显示 'smallguys_name' 代替默认显示的 'smallid'.那是在正常的 php 中,我会选择smallid"并从small"中选择更正的行.我如何在 yii 中做到这一点?

In the _view.php I want to display 'smallguys_name' in place of 'smallid' which is displayed by default. That is in normal php I would have taken 'smallid' and selected the corrected row from 'small'. How do I do it in yii?

我在 _view.php 中有这个 -

I have this in _view.php -

echo $data->smallid;

输出 - 'big' 的 id

output - the id from 'big'

我试过了 -

echo $data->has_small->smallguys_name;

我得到以下 CDbException

and i get the following CDbException

未找到列:1054 Unknown column 'has_small.smallid' in 'where clause'

感谢您的帮助

推荐答案

问题在于,对于HAS_ONE"关系,它试图在 SMALL 表中查询 SMALLID (has_small.smallid) 而不是 ID (has_small.id)).如果 BIG 真的和 SMALL 有HAS_ONE"关系,你需要把 BIG 的外键放在 SMALL 中(翻转它们),像这样:

The problem is that with a "HAS_ONE" relationship, it is trying to query the SMALL table for SMALLID (has_small.smallid) instead of ID (has_small.id). If BIG really has a "HAS_ONE" relationship with SMALL, you need to put the foreign key for BIG in SMALL (flip flop them), like so:

big (id, bigs_name)

big (id, bigs_name)

small(id, smallguys_name, bigid)

small(id, smallguys_name, bigid)

'has_small'  => array(self::HAS_ONE, 'small', 'bigid')

否则,如果您想保持数据库结构不变,我将使用您在评论中提到的 BELONGS_TO 关系:

Otherwise, if you want to keep your DB structure the same, I would use the BELONGS_TO relation like you mentioned in your comment:

'has_small'  => array(self::BELONGS_TO, 'small', 'smallid')

这篇关于yii - 使用关系 HAS_ONE 从相关表中获取数据以显示在列表页面中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 10:27