【问题标题】:Conditional associated models with children models CakePHP带有子模型的条件关联模型 CakePHP
【发布时间】:2018-06-06 17:42:48
【问题描述】:

我有以下数据库结构:

// Contacts
,----,------------,------------------,
| id | name       | email            |
|----|------------|------------------|
| 1  | John Doe   | john@example.com |
'----'------------'------------------'

// Jobs
,----,------------,-------------------,
| id | title      | description       |
|----|------------|-------------------|
| 1  | Fancy Job  | This job is fancy |
'----'------------'-------------------'

// JobRequests
,----,------------,------------,----------,
| id | job_id     | contact_id | accepted |
|----|------------|------------|----------|
| 1  | 1          | 1          | yes      |
| 2  | 1          | 2          | no       |
'----'------------'------------'----------'

我想要所有已接受工作的联系人。

我尝试过以下操作:

$jobs = $this->Jobs
    ->find('all')
    ->where(['event_id' => $id])
    ->contain([
        'JobRequests' => [
            function(Query $query) {
                return $query->where(['JobRequests.accepted' => 'yes']);
            },
            'Contacts'
        ]
    ]);

然后我得到一个 {{Unsupported operand types}} 错误。如果你想要一个条件和一个包含,docs 并没有真正说明你应该做什么。

我该怎么做?

编辑: 我希望数据看起来像这样:

Job 1:
     Accepted by John Doe
     Accepted by Jane Doe
Job 2:
     Accepted by Foo Bar
Job 3:
     Nobody accepted

【问题讨论】:

  • 对于初学者,如果您想接收联系人,您不应该查询Contacts 表吗?您确定您发布了正确的代码,分别正确地描述了您要实现的目标吗?如果您描述关联的类型,并展示您期望结果的样子的示例数据集,这总是有帮助的。
  • 嗯,我需要查询工作表,因为我需要找到工作列表,以及接受这些工作的人。
  • 那样的话只是“语法”不对……

标签: php cakephp associations query-builder cakephp-3.x


【解决方案1】:

您使用了错误的“语法”,您不能只在选项数组中传递一个可调用对象。

在您链接的文档的下方还有一个示例如何嵌套查询构建器并传递其他条件...queryBuilder 选项:

->contain([
    'JobRequests' => [
        'queryBuilder' => function(Query $query) {
            return $query->where(['JobRequests.accepted' => 'yes']);
        },
        'Contacts'
    ]
])

堆叠容器也应该有效:

->contain([
    'JobRequests' => function(Query $query) {
        return $query->where(['JobRequests.accepted' => 'yes']);
    },
    'JobRequests.Contacts'
])

嵌套也应该起作用:

->contain([
    'JobRequests' => function(Query $query) {
        return $query
            ->where(['JobRequests.accepted' => 'yes'])
            ->contain(['Contacts']);
    }
])

另见

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2013-12-02
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多