CakePHP:如何访问嵌套关联字段?

问题描述 投票:0回答:1

我是 CakePHP 的新手。

获取嵌套字段时遇到问题。我不知道 如果其他人以前遇到过同样的问题。

说,我有以下三个表:

  1. 用户

    • id
    • 用户名
    • 密码
    • 注册_ip
  2. 邮寄

    • id
    • user_id
    • 标题
    • 身体
    • posting_ip
  3. 评论

    • id
    • user_id
    • post_id
    • 身体
    • commenting_ip

我想做以下查询:

<?php
    ... 
    $query = $this->getTableLocator()->get("users")->find();
    $query->contain([
        "Posts",        // --> retrieve posts made by a user
        "Comments",     // --> retrieve comments made by a user

        // --> retrieve comments made to a post of a user
        "Posts.Comments" => function ($q) {
            /**
             * Here lies the problem. This is just one example, there
             * might be other examples for this. 
             *
             * I want to select comments to a user's post which IP is 
             * the same as the user's registration IP. 
             * 
             * But when I do, it creates an errors. 
             *  
             * How can multiple dots (nested associations) work in
             * CakePHP?
             * 
             * In Laravel, if I remember correctly, 
             * I was able to do something similar to this. 
             * 
             * I want to use dots to refer to nested associations. 
             * (more than one level).
             */
            return $q->where([
                "Posts.Comments.commenting_ip" => "Users.registration_ip"
            ]);
        }
    ]);

是否可以使用这些链式点来指代更深层次的关联。

我想到的一个可能的解决方案是创建另一个协会 在 UsersTable(比如 CommentsToPosts)中。这可能会破坏嵌套 的帖子和评论。

是否有一个直接的解决方案而无需创建另一个 协会?

非常感谢!希望这个问题将来也可能与其他人的问题有关。

php database cakephp eager-loading
1个回答
0
投票

使用点语法引用嵌套关联并不意味着在条件中使用,您只需在那里使用目标关联别名,因为传递的查询将始终是包含关联表的查询。

此外,如果要比较键/值条件中的字段,则需要使用表达式,例如标识符表达式,否则此类条件的值侧最终会作为绑定参数。

阅读您的评论后,我意识到您没有使

Users
可访问,这是必需的,因为
hasMany
belongsToMany
是在单独的查询中检索的,正如您所注意到的。您可以通过包含从
belongsTo
Comments
Users
关联来实现此目的(如果它不存在,请创建它),这应该将它加入到检索评论的查询中。

$query->contain([
    'Posts.Comments' => [
        'queryBuilder' => function (\Cake\ORM\Query $q) {
            return $q->where([
                'Comments.commenting_ip' => $q->identifier('Users.registration_ip');
            ]);
        },
        'Users',
    ],
]);

另见

© www.soinside.com 2019 - 2024. All rights reserved.