2016-04-20 27 views
1

私はProducts hasMany Tasksです。CakePHP 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のわずか3行のため、このタスクの短いコマンドがあるのでしょうか? SELECT * FROM 'Products' 左外側JOIN' Products' ON Products.id = Task.product_id products.idがnullの場合 – Andrewboy

0

グレッグ・シュミット氏が書いたように: notMatchingは、ソリューションです:

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

または

$query = $articlesTable 
->find() 
->notMatching('Tags', function ($q) { 
    return $q->where(['Tags.name' => 'boring']); 
}); 
関連する問題