【问题标题】:how to write custom query in CakePHP 3.x to retrieve data from joint tables如何在 CakePHP 3.x 中编写自定义查询以从联合表中检索数据
【发布时间】:2016-10-25 03:45:24
【问题描述】:

有 2 张桌子 1:用户

Id | Name |
1    user1
2    user2
3    user3

2:兴趣日志

id | user_id | user_id_Interested_in |
1     1           2
2     1           3
3     2           1
4     2           3
5     3           1
6     3           2

现在在 cakephp 中检索数据和分页的查询如下

$interestLog = $this->paginate($this->interestLog);

$this->set(compact('interestLog'));
$this->set('_serialize', ['interestLog']);

上述查询产生的结果是visitLog表的精确映射。我需要显示名称而不是 Id

我正在尝试产生以下结果。

Id |  USER   |      User Interested In |

1     user1           user2
2     user1           user3
3     user2           user1
4     user2           user3
5     user3           user1
6     user3           user2

但我不知道如何编写自定义查询来产生这个结果。你能给我一些提示吗? 我编写了以下 SQL 查询,该查询运行良好,但如何将其转换为 cakephp 查询

SELECT  il.Id,s.Name , interest.Name FROM users s , users interest , interest_log il
WHERE  s.Id = il.user_id && il.user_id_interested = interest.Id

在 CAKEPHP 3.x 中,我通过以下方式实现了预期的结果

use Cake\Datasource\ConnectionManager;
$conn = ConnectionManager::get('default');

        $result = $conn->execute("SELECT  il.Id,s.Name , visited.Name 
                        FROM users s , users visited , interest_log il
                        WHERE  
                            s.Id = il.user_id 
                            && 
                            il.user_id_interested = visited.Id"
                    );

但是如果有更好的方法在 CAKEPHP 3.x 中编写自定义查询,你能告诉我吗

【问题讨论】:

    标签: sql cakephp-3.0


    【解决方案1】:

    如果你遵循了蛋糕的约定,那就很简单了。 只需尝试在分页数据中包含用户:

    $this->paginate = [
            'contain' => ['Users']
        ];
    $interestLog = $this->paginate($this->interestLog);
    
    $this->set(compact('interestLog'));
    $this->set('_serialize', ['interestLog']);
    

    【讨论】:

    • 实际上我在interestLog表中使用“user id”和“user_id_interested”作为外键引用用户表,我需要显示用户表中的名称与“user id”和“user_id_interested”存在在 InterestLog 表中
    • 哦,我明白了..您可能需要自定义查询,因为您在 user_id_Interested_in 的情况下编写了..
    • 是的,我做了同样的事情,但现在如果我调试然后结果显示正确的数据,但如果我尝试显示则显示 null
    • 如果您分享您用于调试和显示的代码,我们或许可以提供帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    相关资源
    最近更新 更多