CakePHP 3 查找没有关联记录的记录(hasMany)
CakePHP 3 Find records that have no associated record (hasMany)
我有Products hasMany Tasks
.
在任务 table 中查找没有关联记录的所有产品的最佳方法是什么?
我试过:
$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();
正如 Greg Schmidt 所写:notMatching 是解决方案:
$query = $articlesTable->find()->notMatching('Tags');
或
$query = $articlesTable
->find()
->notMatching('Tags', function ($q) {
return $q->where(['Tags.name' => 'boring']);
});
我有Products hasMany Tasks
.
在任务 table 中查找没有关联记录的所有产品的最佳方法是什么?
我试过:
$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();
正如 Greg Schmidt 所写:notMatching 是解决方案:
$query = $articlesTable->find()->notMatching('Tags');
或
$query = $articlesTable
->find()
->notMatching('Tags', function ($q) {
return $q->where(['Tags.name' => 'boring']);
});