我似乎无法理解 CakePHP ORM 模型...
我有一个作者表(带有 Author.ID)和一个图书列表(带有 Book.AuthorID)- 很多书都有一个作者表中不存在的 AuthorID(这是设计使然和预期的)
出于统计原因,我想列出所有具有 AuthorID 且 AuthorID 未在 Authors 表中找到的书籍。
我可以将所有书籍加载到内存中并手动查找 ID - 但大约有 4000 本书。我想以 ORM 方式执行此操作(左外连接?)
谢谢, 三菱商事
最佳答案
这是一个非常简单的 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 Controller 中(如果那是你正在做的事情的 Controller ):
$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();
如果您要从多个 Controller 执行此操作,那么执行此操作的 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']
]);
}
然后你可以在你的 Controller 中调用它们
$with_authors = $this->Books
->find()
->contains(['WithAuthors'])
->all();
$without_authors = $this->Books
->find()
->contains(['WithoutAuthors'])
->all();
关于mysql - CakePHP 显示作者不在作者表中的所有书籍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43233771/