我有Products hasMany Tasks
。CakePHP 3查找没有关联记录的记录(hasMany)
查找所有在任务表中没有关联记录的产品的最佳方法是什么?
我已经试过:
$query->matching('Tasks', function ($q) {
return $q->where(['Tasks.product_id' => NULL});
但是,这似乎并没有这样的伎俩。
您使用 子查询这是要找到没有相关的记录中所有产品的最简单的方法..
我有Products hasMany Tasks
。CakePHP 3查找没有关联记录的记录(hasMany)
查找所有在任务表中没有关联记录的产品的最佳方法是什么?
我已经试过:
$query->matching('Tasks', function ($q) {
return $q->where(['Tasks.product_id' => NULL});
但是,这似乎并没有这样的伎俩。
您使用 子查询这是要找到没有相关的记录中所有产品的最简单的方法..
我建议试试这个:
$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();
我想知道这个任务是否有一个较短的命令,因为在mysql中它只有三行: SELECT * FROM'Products' Left External JOIN' Products' ON Products.id = Task.product_id where products.id IS null – Andrewboy
格雷戈·施密特写道: notMatching是解决方案:
$query = $articlesTable->find()->notMatching('Tags');
或
$query = $articlesTable
->find()
->notMatching('Tags', function ($q) {
return $q->where(['Tags.name' => 'boring']);
});
如果您使用3.1或更高版本,[notMatching](http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#using-notmatching)可能是解决方案。 –