我有一个有效的SQL查询我想弄清楚CakePHP查询构建器的等效工作方式完全相同吗?
SELECT customers.*, customer_reps.created FROM customers
LEFT JOIN customer_reps ON customer_reps.id =
(
SELECT id FROM customer_reps WHERE customer_id = customers.id
ORDER BY id ASC LIMIT 1
)
WHERE created >= 1475298000
AND created <= 1476217836
AND agents_id = 4
基本上我从“客户”中选择所有列,然后我只想要第一个“customer_reps”表的“创建”时间戳字段来匹配客户。
关于CakePHP的文档似乎没有解释如何在select中进行select以进行排序。我尝试使用“hasMany”关系的东西,但我无法找到如何只是获取“第一个”customer_reps条目添加到主要查询以便在WHERE子句中使用。
由于
答案 0 :(得分:0)
尝试使用此代码作为起点,您只需要按CustomerRep.customer_id对其进行分组,因为如果您的customer_reps表ID已自动递增,则订单已经提升
$this->Customer->find('all', array(
'fields' => arrray(
'Customer.*',
'CustomerRep.created'
),
'joins' => array(
array(
'type' => 'LEFT',
'table' => 'customer_reps',
'alias' => 'CustomerRep',
'conditions' => 'Customer.id = CustomerRep.customer_id'
)
)
'conditions' => array(
'Customer.created >=' => '1475298000',
'Customer.created <=' => '1476217836',
'Customer.agentds_id' => 4
),
'group' => 'CustomerRep.customer_id'
));
答案 1 :(得分:0)
你熟悉cakephp查询构建器吗?如果是的话你应该理解这个流程
第1步:cakephp中的SELECT customers.*, customer_reps.created FROM customers
等价物是
$this->Customer->find('all', array(
'fields' => array(
'Customer.*',
'CustomerReply.created'
)
);
注意:CustomerReply.created
来自customer_reps
的联接表,我只是别名CustomerReply
第2步:cakephp中的LEFT JOIN customer_reps ON customer_reps.id =
(
SELECT id FROM customer_reps WHERE customer_id = customers.id
ORDER BY id ASC LIMIT 1
)
等效项
'joins' => array(
array(
'table' => 'customer_reps',
'type' => 'left',
'alias' => 'CustomerReply',
'conditions' => array(
'CustomerReply.id = (SELECT id FROM customer_reps WHERE customer_id = Customer.id ORDER BY id ASC LIMIT 1)'
)
))
第3步:cakephp中的WHERE created >= 1475298000
AND created <= 1476217836
AND agents_id = 4
等价物是
'conditions' => array(
'Customer.created >=' => 1475298000,
'Customer.created <=' => 1476217836,
'Customer.agents_id' => 4
)
);
所以你的cakephp查询构建器就像这样
$query = $this->Customer->find('all', array(
'fields' => array(
'Customer.*',
'CustomerReply.created'
),
'joins' => array(
array(
'table' => 'customer_reps',
'type' => 'left',
'alias' => 'CustomerReply',
'conditions' => array(
'CustomerReply.id = (SELECT id FROM customer_reps WHERE customer_id = Customer.id ORDER BY id ASC LIMIT 1)'
)
)),
'conditions' => array(
'Customer.created >=' => 1475298000,
'Customer.created <=' => 1476217836,
'Customer.agents_id' => 4
)
));