【问题标题】:CakePHP show all books whose author is not in the authors tableCakePHP 显示所有作者不在作者表中的书籍
【发布时间】:2017-04-05 14:13:59
【问题描述】:

我似乎无法理解 CakePHP ORM 模型...

我有一个 Authors 表(带有 Author.ID)和一个书籍列表(带有 Book.AuthorID) - 许多书籍的 AuthorID 不存在于 Authors 表中(这是设计使然,并且是预期的) )

出于统计原因,我想列出所有具有 AuthorID 且 AuthorID 未在 Authors 表中找到的图书。

我可以将所有书籍加载到内存中并手动查找 id - 但是大约有 4000 本书。我想以 ORM 方式执行此操作(左外连接?)

谢谢, MC

【问题讨论】:

  • 那么您的问题是如何使用 CakePHP 查询构建器定义左连接,或者您是在问是否应该在第一个地方使用左连接?
  • 我觉得this这个问题也可能有用

标签: mysql cakephp orm cakephp-3.0


【解决方案1】:

这是一个非常简单的 orm 任务。正如 cmets 中提到的@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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    相关资源
    最近更新 更多