2016-04-20 606 views
1

我有Products hasMany TasksCakePHP 3查找没有关联记录的记录(hasMany)

查找所有在任务表中没有关联记录的产品的最佳方法是什么?

我已经试过:

$query->matching('Tasks', function ($q) { 
return $q->where(['Tasks.product_id' => NULL}); 

但是,这似乎并没有这样的伎俩。

您使用 子查询

这是要找到没有相关的记录中所有产品的最简单的方法..

+1

如果您使用3.1或更高版本,[notMatching](http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#using-notmatching)可能是解决方案。 –

回答

4

我建议试试这个:

$matchingTasks= $this->Products->association('Tasks')->find() 
     ->select(['product_id'])// id of product in Tasks Table 
     ->distinct(); 

    $query = $this->Products->find() 
     ->where(['id NOT IN' => $matchingTasks]); 
    // to debug the result 
     foreach($query as $product){ 
     debug($product); 
    } 
    die(); 
+0

我想知道这个任务是否有一个较短的命令,因为在mysql中它只有三行: SELECT * FROM'Products' Left External JOIN' Products' ON Products.id = Task.product_id where products.id IS null – Andrewboy

0

格雷戈·施密特写道: notMatching是解决方案:

$query = $articlesTable->find()->notMatching('Tags'); 

$query = $articlesTable 
->find() 
->notMatching('Tags', function ($q) { 
    return $q->where(['Tags.name' => 'boring']); 
}); 
相关问题