gpt4 book ai didi

php - CakePHP 3 - 从用户正在关注的用户加载帖子

转载 作者:可可西里 更新时间:2023-11-01 07:09:29 25 4
gpt4 key购买 nike

尝试以“Cakey”方式加载用户正在关注的用户的所有帖子。

三个表:

用户(id、用户名、密码)

posts (id, text, user_id, created)

关注(id、user_id、following_id)

我认为我的关系设置正确,所以我可以加载用户关注者和关注他们的人:

用户表

    $this->belongsToMany('Following', [
'className' => 'Users',
'foreignKey' => 'user_id',
'targetForeignKey' => 'following_id',
'joinTable' => 'follows'
]);

$this->belongsToMany('Followers', [
'className' => 'Users',
'foreignKey' => 'following_id',
'targetForeignKey' => 'user_id',
'joinTable' => 'follows'
]);

遵循表格

    $this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);

帖子表

    $this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);

现在很难从单个用户关注的用户中选择所有帖子。我想我需要使用此处记录的 matching() 方法:Filtering by Associated Data Via Matching And Joins但似乎没有做对。

沿着这些方向尝试:

$user_id = $this->Auth->user('id');

$posts = $this->Posts->find()->matching('Users.Following', function ($q) use ($user_id) {
return $q->where(['Users.id' => $user_id]);
})->all();

UPDATE:

我认为我的关系设置正确,此查找将返回用户以及他们关注的所有用户:

  $users = $this->Posts->Users->get(1, [
'contain' => ['Following']
]);

最佳答案

您错过了将 $user_id 继承给匹配的匿名函数

$user_id = $this->Auth->user('id');

$posts = $this->Posts->find()
->matching('Users.Following', function ($q) use ($user_id) {
return $q->where(['Users.id' => $user_id]);
})
->all();

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. From PHP 7.1, these variables must not include superglobals, $this, or variables with the same name as a parameter.

另见 Anonymous functions

UPDATE:

添加到用户表

$this->hasMany('Posts', [
'className' => 'Posts',
'foreignKey' => 'user_id'
]);

Controller

$users = $this->Posts->Users->get(1, [
'contain' => ['Following.Posts']
]);

关于php - CakePHP 3 - 从用户正在关注的用户加载帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44166045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com