【问题标题】:Cakephp contains association when using matching()Cakephp在使用matching()时包含关联
【发布时间】:2015-10-22 10:29:29
【问题描述】:

在我的项目中,我有以下表格:MessagesRecipientsGroupsUsers。一个Message 有多个Recipients,一个Recipient 有一个Group 和一个User

在我的 RecipientsTable::beforeFind 中,我有一些代码可以自动包含 GroupsUsers 以查找 Recipient,因为我总是需要访问这些关联。

public function beforeFind($event, $query, $options, $primary) {
    return $query->contain([
        'Groups',
        'Users',
    ]);
}

我不知道这是否是一个糟糕的设计决定,但到目前为止它对我很有用。

现在问题来了,我正在尝试按组过滤消息,我尝试使用matching 函数来这样做:

$possible_groups = [1,2,3]; //just an example
$query->matching('Recipients', function($q) use ($possible_groups){
            return $q->where(['Recipients.group_id IN' => $possible_groups]);
});

当我执行查询时,我收到以下错误:

Messages is not associated with Groups

有没有办法让我的 beforeFind 保持这种状态并能够使用匹配?或者,有没有更好的方法来自动加载关联而不使用 beforeFind?

TL;DR: A hasMany B, B hasOne C. 如果对表 A 的查询在表 B 上使用 matching 并且表 B 的 beforeFind 使用 contain 加载 C,则 C 最终包含在原始查询中( A) 并且执行失败,因为 A 与 C 没有关联。

【问题讨论】:

  • "有没有更好的方法来自动加载关联而不使用 beforeFind?"是的
  • @Salines,如果您提供一些详细信息可能会更有帮助...

标签: cakephp cakephp-3.0


【解决方案1】:

使用表格类自动加载表格关联。就像在必要的表类中使用 hasMany()、hasOne()、belongsTo()、belongsToMany() 一样。

官方文档:
https://book.cakephp.org/3.0/en/orm/associations.html

表格文件应位于 Model 文件夹内的 Table 文件夹中,例如 src\Model\Table。

【讨论】:

    猜你喜欢
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    相关资源
    最近更新 更多