我有3张桌子,restaurants
,orders
,users
。订单表有字段restaurant_id
,status
和user_id
。
restaurant -> hasMany orders
orders belogsTo Restaurant
orders belongsTo users
我只需找到那些订单状态为1的餐馆,同时需要获取用户的信息。
所以,我正在与订单表进行内部联接,
$options['joins'] = array(
array('table' => 'orders',
'alias' => 'Order',
'type' => 'INNER',
'conditions' => array(
'Restaurant.id = Order.restaurant_id',
)
)
);
但是我怎样才能获得用户的信息,因为根据蛋糕文件http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#joining-tables,这里允许的参数是table, alias, type, conditions
。有没有办法在最终查询中嵌入获取用户信息的sql查询?是的,另一种方法是编写自定义查询,但是没有办法处理蛋糕。
谢谢
更新
在这种情况下,最好的解决方案是编写自定义sql查询。
你刚刚尝试过额外的加入以获得用户吗?
像这样的东西:
$this->Restaurant->find('all', array(
'joins' => array(
array('table' => 'orders',
'alias' => 'Order',
'type' => 'INNER',
'conditions' => array(
'Restaurant.id = Order.restaurant_id',
'Order.status = 1'
)
),
array('table' => 'users',
'alias' => 'User',
'type' => 'RIGHT',
'conditions' => array(
'Order.user_id = User.id'
)
),
));
注意:我通常最容易找到的(使用复杂的查询,您无法搞清楚)是在SQL中100%构建查询并使其按照您的喜好工作,然后在CakePHP中重新构建它。
状态为1且包含餐馆和用户信息的订单列表:
$this->Restaurant->Order->find('all', array('conditions'=>array('Order.status'=>1), 'contain'=>array('Restaurant', 'User')))