【问题标题】:Is it possible to use find('list') with Containable behavior in CakePHP 3?是否可以在 CakePHP 3 中使用具有可包含行为的 find('list') ?
【发布时间】:2020-06-22 04:22:25
【问题描述】:

应用程序使用的是 CakePHP 3.5.18 版

我已经使用 ORM 获得了一个返回键/值对的列表:

$Displays = TableRegistry::get('Displays');
$displays = $Displays->find('list', ['keyField' => 'id', 'valueField' => 'id'])->where(...)->toArray();

这按预期工作。 debug($displays); 的示例如下所示:

(int) 36 => (int) 36,
(int) 160 => (int) 160,
(int) 149 => (int) 149,
...

在这个特定的应用程序中,有 3 个模型在以下层次结构中工作:

  • 规则(1级。表名regulations
    • 组(2级。表名groups
      • 显示(3 级。表名displays

应用程序已被烘焙,以便在 Table 类中定义适当的关系。

// src/Model/Table/RegulationsTable.php
$this->hasMany('Groups', [
    'foreignKey' => 'regulation_id'
]);

// src/Model/Table/GroupsTable.php
$this->hasMany('Displays', [
    'foreignKey' => 'group_id'
]);

// src/Model/Table/DisplaysTable.php
$this->belongsTo('Groups', [
    'foreignKey' => 'group_id',
    'joinType' => 'INNER'
]);

我要做的是调整$displays 定义的查询,使结果对应于Regulations.id 的给定数组。假设 ID 为 1、2 和 3,我正在尝试做的普通 SQL 等价物是 ... WHERE regulations.id IN (1,2,3)

当我阅读 Passing conditions to contain 上的 Cake 文档时,它说:

当您限制从关联中获取的字段时,您必须确保选择外键列。未能选择外键字段将导致最终结果中不存在关联数据。

我不明白find('list') 怎么可能,因为它只选择开发人员指定的keyFieldvalueField?在这种情况下,两者都是displays.id

无论如何我不明白如何编写这个查询,因为在同一个链接文档中它说

使用contain() 时,您可以限制关联返回的数据并按条件过滤它们。要指定条件,请传递一个匿名函数,该函数接收一个查询对象\Cake\ORM\Query作为第一个参数

contain() 实际操作的是什么:我假设它是 Regulations,但不知道如何写。

【问题讨论】:

    标签: php cakephp orm cakephp-3.0


    【解决方案1】:

    我认为您需要通过匹配而不是通过包含来查看过滤数据。 (如果我理解正确的话。)

    您可以将find('list')->matching(...) 结合使用:

    $displays = $this->Displays->find('list')
        ->matching('Groups.Regulations', function ($q) use ($ids) {
            return $q->where(['Regulations.id IN' => $ids]);
        })
        ->toArray();
    

    (尚未测试)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 1970-01-01
      • 2015-04-03
      相关资源
      最近更新 更多