CakePHP 2.x:加入belongssto

时间:2014-02-07 17:40:13

标签: mysql cakephp join belongs-to

在我的模型'mesn'中,我有属于关系:

    public $belongsTo = array(
        'Order' => array(
            'className' => 'Order', 'foreignKey' => 'order_id', 'conditions' => '', 'fields' => '', 'order' => ''
        ), 'SaleOrder' => array(
            'className' => 'SaleOrder', 'foreignKey' => 'sale_order_id', 'conditions' => '', 'fields' => '',
            'order' => ''
        ), 'ShippedBox' => array(
            'className' => 'Box', 'foreignKey' => 'shipped_box_id', 'conditions' => '', 'fields' => '',
            'order' => ''
        )
    ); /*     * * hasMany associations** @var array

在我的一个模型函数中,我想在“belongssto”“ShippedBox”(表格:框)上加入另一个表格。但无论我如何尝试编写连接,我都会收到一条未知列的错误消息:

$arr_s_result = $this->find('all', array(
  'joins' => array(
    array('table' => 'shipments',
      'alias' => 'MyShipments',
      'type' => 'INNER',
      'conditions' => array(
      'MyShipments.id = ShippedBox.shipment_id'
    )
  )),
  'conditions' => array('Mesn.name' => $arr_search), 'recursive' => 0
));

我试过了:

'MyShipments.id = ShippedBox.shipment_id'

'MyShipments.id = box.shipment_id'

甚至

'MyShipments.id = Boxes.shipment_id'

其中包含字段“shipment_id”的表“框”。

我如何让这个加入工作?

2 个答案:

答案 0 :(得分:0)

'MyShipments.id = box.shipment_id'

为:

'MyShipments.id = Box.shipment_id'

还有这个:

$arr_s_result = $this->find('all', array(
                              'conditions' => array('Mesn.name' => $arr_search), 'recursive' => 0

));

belongsTo联接自动完成。

答案 1 :(得分:0)

我认为你需要做一些像使用子查询来获得你想要的东西 -

$arr_s_result = $this->find('all', array(
     'joins' => array(
          array('table' => '(SELECT boxes.id, [enter other fields you need here] FROM shipments JOIN boxes ON boxes.shipment_id = shipments .id)',
          'alias' => 'MyShipments',
          'type' => 'INNER',
          'conditions' => array(
        'Mens.shipped_box_id = MyShipments.id'
       )
    )),
  'conditions' => array('Mesn.name' => $arr_search), 'recursive' => 0
));