正在处理具有以下对象的项目:
人
车辆
和用于所有者更改的所有者链接表
我正尝试在人员的视图上添加一个自定义查询,该查询仅选择具有某种车辆类型的人(用于发送新闻通讯)。为此,我提供有关此人的车辆的一些有价值信息的唯一途径是通过
453 //Conditions
454 $conditions['receives_news'] = 1;
455 $conditions['and'] = array("not" => array("email" => null), "not" => array("email" => ''));
456 $conditions['Person.receives_news'] = '1';
457 $conditions['LOWER(Vehicle.model) LIKE'] = strtolower("%$vehicleModel%");
458 //$conditions['Person.id'] = '1';//hitme
459
460 $this->Person->recursive = 2;//Limit to 1 if too slow and remove from view the Provider Name
461 $joins = array();
462 $joins[] = array(
463 'table' => 'owner_changes',
464 'conditions' => 'Person.id = OwnerChange.new_person_id',
465 'type' => 'INNER',
466 'alias' => 'OwnerChange',
467 );
468 $joins[] = array(
469 'table' => 'vehicles',
470 'conditions' => 'OwnerChange.vehicle_id = Vehicle.id',
471 'type' => 'INNER',
472 'alias' => 'Vehicle',
473 );
474 $this->paginate = array('conditions' => $conditions,
475 'group' => 'Person.id',
476 'joins' => $joins,
477 'maxLimit' => 250,
478 'limit' => 20);//Optional
479 $data = $this->paginate();
480
481 //debug($data, 4);
482 $this->set(strtolower($this->name), $data);
我的问题是我在人和车辆之间拥有所有关联,我只想将它们限制为最新的关联(by date DESC LIMIT 1
),并且联接的结构未考虑我输入的订购或限制条款。所以我有属于其他人的车辆!!!
我尝试了类似this post之类的尝试,但没有成功 似乎通常是“ 每组最大的麻烦”(this question),即使在SQL级别上,我仍然没有答案
我现在找到了足够的查询来获取我的结果,但是无法将其集成到cakephp中。查询为:
SELECT p.`id` AS person_id, p.`name`, p.`surname`, p.`email`, p.`city`, p.`receives_news` , v.`model`, v.`id` AS vehicle_id, o.date AS owner_change_date
FROM owner_changes o
JOIN people p on o.new_person_id = p.id
JOIN vehicles v on o.vehicle_id = v.id
JOIN (select oc.vehicle_id, max(oc.date) maxdate
FROM owner_changes oc
GROUP by oc.vehicle_id) last1 ON o.vehicle_id = last1.vehicle_id
and o.date = last1.maxdate
WHERE p.`receives_news` = '1' AND NOT (p.`email` = '') AND LOWER(v.`model`) LIKE '%mts%'
ORDER BY v.`id` ASC, o.`date` DESC
LIMIT 200