Find conditions like 'NOT EXISTS'

孤街醉人 提交于 2019-12-12 19:12:15

问题


I have 2 tables in my db...

Entita
id int(11)
descrizione varchar(50)
.....

Publicobjects
....
model varchar(50) the model I need (in this case 'Entita')
model_id int(11)

I would like to make a query like this:
select entita.* from entita where NOT EXISTS (select * from publicobjects where publicobjects.model = 'Entita' and publicobjects.model_id = entita.id)

How can I do this with the model functions of Cakephp without use custom query?

Thanks


回答1:


I believe you're trying to find rows from the Entita table that are not in the Publicobjects table. Assuming that is correct, here is the SQL query for MySQL to find it:

SELECT `entita`.*
FROM `entita` 
LEFT JOIN `publicobjects` ON (`publicobjects`.`model` = 'entita' 
    AND `publicobjects`.`model_id` = `entita`.`id`)
WHERE `publicobjects`.`model_id` IS NULL

To make this work with CakePHP's models takes a couple of steps. I've made some assumptions about your model names, but I could be wrong and those are easy to fix.

First add this to the Entita model:

<?php
var $hasOne = array('Publicobject' => array(
    'foreignKey' => 'model_id',
    'conditions' => 'Publicobject.model = "Entita"'));

Now, you can check for entries that are missing in the Publicobjects table like this:

<?php
$this->Entita->find('all', array('conditions' => array('Publicobject.model_id IS NULL')));


来源:https://stackoverflow.com/questions/1916286/find-conditions-like-not-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!