Reputation: 1740
I have Products hasMany Tasks
.
What is the the best way to find all products that do not have an associated record in the tasks table?
I've tried with:
$query->matching('Tasks', function ($q) {
return $q->where(['Tasks.product_id' => NULL});
But that doesn't seem to do the trick.
Upvotes: 3
Views: 920
Reputation: 61
As Greg Schmidt wrote: notMatching is the solution:
$query = $articlesTable->find()->notMatching('Tags');
or
$query = $articlesTable
->find()
->notMatching('Tags', function ($q) {
return $q->where(['Tags.name' => 'boring']);
});
Upvotes: 5
Reputation: 1304
I advice you to use Subqueries
It's the simplest way to to find all Products that do not have an associated record .. Try this :
$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();
Upvotes: 4