CakePHP从另一个模型中检索数据

时间:2014-03-22 04:23:40

标签: php cakephp model

我是cakephp的新手,我从另一个模型中检索数据时遇到了一些问题。

我的表格关联是这样的:

Items hasMany Stocks

Stocks belongsTo Items

Items belongsTo UnitMeasurement

UnitMeasurement hasMany Items

我的问题是我想将UnitMeasurement Name显示为Stocks索引html表视图。

当前的Html表格视图:

----------------------------------------------------------------------
Item           | Stock Balance|          Unit          |     Created |
----------------------------------------------------------------------
Microprocessor |    12        | DISPLAY UNIT NAME HERE!| 19/1/2014   |
Microcontroller|    20        | DISPLAY UNIT NAME HERE!| 19/1/2014   |             
CPU            |    12        | DISPLAY UNIT NAME HERE!| 19/1/2014   |             
----------------------------------------------------------------------

如何制作成功的查询?

感谢。

编辑:

这是我在StocksController索引函数中的查找查询:

public function index() {
        $this->Stock->recursive = 0;
        $order = "Stock.id DESC";
        //set orderby
        $stock = $this->Stock->find('all',array('order'=>$order));
        $this->set('stocks', $stock);

        //query to find UnitMeasurement Name for Stocks Item
        foreach ($stock as $stocks) {
            //debug($stocks);
            $this->loadModel('Items');
            $unitMeasurement = $this->Items->find('first',array('fields'=>'unit_measurement_id','conditions'=>array('Items.id'=>$stocks['Stock']['item_id'])));
            $this->set('units',$unitMeasurement);
        }

    }

再次感谢。

2 个答案:

答案 0 :(得分:0)

检查这个型号名称总是单数请检查并告诉我它是否有效!

foreach ($stock as $stocks) {
            //debug($stocks);
            //$this->loadModel('Items');
            $this->loadModel('Item');
            $unitMeasurement = $this->Item->find('first',array('fields'=>'unit_measurement_id','conditions'=>array('Item.id'=>$stocks['Stock']['item_id'])));
            $this->set('units',$unitMeasurement);
        }

答案 1 :(得分:0)

你可以这样做一个查询:

$items = $this->Item->find('all', array(
    'fields' => array(
        'Item.name',
        'SUM(Stock.amount) as amount',
        'UnitMeasurement.name',
        'Item.created',
    ),
    'joins' => array(
        array(
            'table' => "stocks",
            'alias' => "Stock",
            'conditions' => "Item.id = Stock.item_id"
        ),
        array(
            'table' => 'unit_measurements',
            'alias' => 'UnitMeasurement',
            'conditions' => 'UnitMeasurement.id = Item.unit_measurement_id',
        ),      
    ),
    'group' => array('Item.id', 'Item.unit_measurement_id'),
));