2017-04-05 6 views
0
私はCakePHPのORMモデルの周りに私の頭をラップすることができないよう

... CakePHPはその著者authorsテーブルに存在しないすべての書籍

私は(Author.ID付き)テーブルの著者を持って

し、リストを表示します(Book.AuthorID付き) - 多くの書籍にAuthors Tableに存在しないAuthorIDがあります(これは設計上のもので、予期されています)。

統計的な理由から、 AuthorIDとAuthorIDがAuthorsテーブルに見つかりません。

私はすべての本をメモリにロードし、手でIDを調べることができますが、約4000冊の本があります。私はORMの方法でこれを行うにはしたいと思います(外部結合左?)

おかげで、 MC

+2

でこれらを呼び出すことができますが、CakePHPのクエリビルダで参加するか、最初palceに参加あなたは左を使用するかどうかを尋ねていますか? – ndm

+0

私は[this](http://stackoverflow.com/questions/39558115/find-by-conditions-on-associated-model-in-cakephp-3)の質問も使用するかもしれないと思います – Warren

答えて

2

これは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();