Yii Joined表,但未检索到所有选定数据 [英] Yii Joined table but not all selected data is retrieved

查看:94
本文介绍了Yii Joined表,但未检索到所有选定数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中具有以下条件.

I have the following criteria in my controller.

    $criteria = new CDbCriteria;
    $criteria->select = 't.*,b.*,c.*';
    $criteria->join = "INNER JOIN tbl_patient_chair b ON b.patient = '0005'
                        INNER JOIN tbl_chair c ON b.chair = c.Serial_No";
    $criteria->condition = "t.client_id = '0005'";

    $model = Patient::model()->findAll($criteria);

    $this->render('view', array(
        'model' => $model
    ));

然后在我看来,我试图通过执行以下操作来检索所有选定的数据:

Then in my view I am trying to retrieve all the selected data by doing:

foreach ($model as $models)
  print_r($model);

但是在结果中,我可以看到第二个和第三个表中没有数据.第一个表的数据已成功检索,但是我无法显示另一个表的数据.

But in the result I can see that there is no data from second and third table. The data of the first table is successfully retrieved however I cannot display the other table's data.

有人可以告诉我我在做什么错吗?

Can anyone tell me what I am doing wrong?

推荐答案

在Yii中,最好通过创建Relations来使用联接,这样就无需编写复杂的查询

Joins are best used in Yii by creating Relations , that way you won't need to write complex queries

首先在sql表中添加外键 (例如,在椅子上添加外键PatientId)

Start by adding foreign keys in your sql tables (eg add a foreignkey patientId in chair)

下一步,如果重新生成模型,则可以看到自动添加的关系(或者可以手动添加关系)

Next if you regenerate your model you can see the relations auto-added (or you can manually add the relations)

public function relations()
{

    return array(
        'chairs' => array(self::HAS_MANY, 'chair', 'patientId'),
    );
}

在椅子模型中,您将看到这种关系

And in the chair model you will see the relation

'patient' => array(self::BELONGS_TO, 'patient', 'patientId'),

仅通过定义关系就可以以$ model-> relationName的形式访问查询的模型中的值,如果要在"where"条件下使用列,请在模型函数中使用以下查询

Defining the relation alone allows you access to the values in queried model as $model->relationName, if you want to use a column in 'where' condition, use the following query in your model function(s)

$patients=Patient::model()->findAll(array(
                'condition' => "$field like '%$value%'",
                'with'=>array('chairs'),
                'select'=> "*",
                )); 

"with"关键字很重要,可以采用一系列关系列表来包括在查询中.查询条件将适用于所有包含的表.如果不想查询另一个表中的字段,而只需要链接输出数据,则可以在此处跳过"with"关键字.

The "with" keyword is important and can take an array of list of relations to include in the query. The query condition will apply to all the tables included, You can skip the "with" keyword here if you do not want to query a field from another table and only need the output data linked.

您就可以到达

foreach($patients as $patient)print_r($patient->chairs);

还有其他方法,例如讨论的

There are other approaches too , like one discussed here

要获取与关系的更多联系,请在此处

To get more in touch with relations, go here

这篇关于Yii Joined表,但未检索到所有选定数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆