mysql - CakePHP 显示作者不在作者表中的所有书籍

标签 mysql cakephp orm cakephp-3.0

我似乎无法理解 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/

相关文章:

mysql - innoDB MySQL 中的关键字研究

php - 我如何从 2 个数据库表中选择并将内容限制在 40 个?

mysql - 使用 Amazon Web Services(EC2 等)托管 CakePHP 应用程序?

java - 最新的 hibernate (5) 是否适用于数组类型?

java - JPA 如何知道如何使用连接表链接列和实体?

java - Hibernate 不会加载一对多的关系集,即使使用 eager fetch

php - 如何使用内连接创建类别?

mysql - 多表删除时出现语法错误

php - 包括相关表中的单个项目

php - 使用 Cakephp 2.x 选择 id 不在另一个表中的所有记录