我似乎无法绕过CakePHP ORM模型......
我有一个表Authors(带有Author.ID)和一个书籍列表(带有Book.AuthorID) - 很多书都有一个AuthorID,在作者表中不存在(这是设计和预期的)
出于统计原因,我想列出所有具有AuthorID的书籍,并且在作者表格中找不到AuthorID。
我可以将所有书籍加载到内存中并手动查找id - 但是有大约4000本书。我想以ORM方式执行此操作(左外连接?)
谢谢, MC
答案 0 :(得分:3)
对于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控制器中(如果那是你正在做的控制器):
$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();