Yii加入两个模型

时间:2014-03-15 12:46:45

标签: php mysql yii

我有两个mysql表: 价格 2.详情

表格价格

ID  |  DATE     | CODE |  PRICE
1   |2014-01-01 | AAA1 | 90.123
2   |2014-01-01 | AAB1 | 50.113
3   |2014-01-01 | AAC1 | 48.621
4   |2014-01-02 | AAA1 | 91.123
5   |2014-01-02 | AAB1 | 51.113
6   |2014-01-02 | AAC1 | 41.621

表格详情

CODE | NAME   | DESCRIPTION
AAA1 | andria | A very good...
AAB1 | anasta | A very good...
AAC1 | simple | A very good...

型号:

价格

public function relations(){
        return array(
            'code' => array(self::BELONGS_TO, 'details', 'code'),
        );
    }

详情

public function relations(){
        return array(
            'code' => array(self::HAS_MANY, 'prices', 'code'),
        );
    }

这是我想要执行的SQL代码:

SELECT * FROM prices a 
JOIN (SELECT * FROM details) b
WHERE a.DATE=(SELECT MAX(DATE) FROM prices) AND a.code = b.code

我的控制器:

$prices=new CActiveDataProvider('prices', array(
                'criteria'=>new CDbCriteria (array(
                    'select'=>'code,date,close',
                    'condition'=>'date=(SELECT MAX(date) FROM prices)'
                )),
            ));

$this->render('index',array(
                'prices'=>$prices
            ));

的index.php:

<?php 
    $this->widget('bootstrap.widgets.TbGridView', array(
    'dataProvider'=>$prices,
    'template'=>"{items}",
    'enablePagination' => false,
    'columns'=>array(
        array('name'=>'code', 'header'=>'Code'),
        array('name'=>'name', 'header'=>'Name'),
        array('name'=>'close', 'header'=>'Close'),
    ),
)); ?>

使用此控制器命令,我可以从表格中获取数据,但我无法从表格详细信息中获取数据。

3 个答案:

答案 0 :(得分:1)

查看标准的with部分:http://www.yiiframework.com/doc/api/1.1/CDbCriteria#with-detail

我认为您的代码看起来像这样(未经测试):

$prices=new CActiveDataProvider('prices', array(
            'criteria'=>new CDbCriteria (array(
                'select'=>'code,date,close',
                'with' => 'details',
                'condition'=>'date=(SELECT MAX(date) FROM prices)'
            )),
        ));

答案 1 :(得分:1)

你已经在模特中得到了回应。所以在你的控制器中这样查询

$prices=new CActiveDataProvider('prices', array(
        'criteria'=>new CDbCriteria (array(
            'condition'=>'date=(SELECT MAX(date) FROM prices)'
        )),
    ));

在视图中使用

$data->code->name
$data->code->description

答案 2 :(得分:0)

以下是我改变的内容:

<强>的index.php

<?php 
    $this->widget('bootstrap.widgets.TbGridView', array(
    'dataProvider'=>$prices,
    'template'=>"{items}",
    'enablePagination' => false,
    'columns'=>array(
        array('name'=>'code', 'header'=>'Code'),
        array('name'=>'name', 'header'=>'Name', 'value'=>'$data->details->name'),
        array('name'=>'close', 'header'=>'Close'),
    ),
)); ?>

型号价格

public function relations(){
        return array(
            'details' => array(self::BELONGS_TO, 'Stocks_details', 'code'),
        );
    }