これはORMとかなり簡単な作業です。 @ndmはコメントの中で述べたように、belongsToの関連付けのデフォルトである左の結合でこれを行うことができます。 BooksTableで
関連付けが初期化メソッドに追加されていることを確認します
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('books');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->belongsTo('Authors', [
'foreignKey' => 'author_id'
]);
}
あなたの本コントローラでは(それはあなたがで物事をやっているコントローラの場合):
$books_without_authors = $this->Books
->find()
->contain(['Authors'])
->where(['Authors.id IS NULL'])
->all();
$books_with_authors = $this->Books
->find()
->contain(['Authors'])
->where(['Authors.id IS NOT NULL'])
->all();
の場合あなたは複数のコントローラーからこれをやろうとしていますし、それを行うDRY方法は関連としてあります:
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('books');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->belongsTo('Authors', [
'foreignKey' => 'author_id'
]);
$this->belongsTo('WithAuthors', [
'className' => 'Authors',
'foreignKey' => 'author_id',
'joinType' => 'INNER'
]);
$this->belongsTo('WithoutAuthors', [
'className' => 'Authors',
'foreignKey' => 'author_id',
'conditions' => ['Authors.id IS NULL']
]);
}
あなたがそのようにあなたの質問が左を定義する方法である、あなたのコントローラ
$with_authors = $this->Books
->find()
->contains(['WithAuthors'])
->all();
$without_authors = $this->Books
->find()
->contains(['WithoutAuthors'])
->all();
でこれらを呼び出すことができますが、CakePHPのクエリビルダで参加するか、最初palceに参加あなたは左を使用するかどうかを尋ねていますか? – ndm
私は[this](http://stackoverflow.com/questions/39558115/find-by-conditions-on-associated-model-in-cakephp-3)の質問も使用するかもしれないと思います – Warren