Kyl*_*lan 5 php mysql database cakephp cakephp-3.0
尝试加载用户以"Cakey"方式关注的用户的所有帖子.
三张桌子:
用户(id,用户名,密码)
帖子(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'
]);
Run Code Online (Sandbox Code Playgroud)
按照表格
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
Run Code Online (Sandbox Code Playgroud)
帖子表
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
Run Code Online (Sandbox Code Playgroud)
现在努力选择单个用户跟随的用户的所有帖子.我认为我需要使用matching()此处记录的方法:通过匹配和联接按关联数据进行过滤,但似乎没有做到正确.
尝试这些方面的东西:
$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();
Run Code Online (Sandbox Code Playgroud)
更新:
我认为我的关系设置正确,此查找将返回用户以及他们所关注的所有用户:
$users = $this->Posts->Users->get(1, [
'contain' => ['Following']
]);
Run Code Online (Sandbox Code Playgroud)
您错过了继承$user_id到matching anonymous function.
$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();
Run Code Online (Sandbox Code Playgroud)
闭包还可以从父作用域继承变量。任何此类变量都必须传递给 use 语言构造。从 PHP 7.1 开始,这些变量不得包含superglobals、
$this、 或与参数同名的变量。
另请参见匿名函数
更新:
添加到用户表
$this->hasMany('Posts', [
'className' => 'Posts',
'foreignKey' => 'user_id'
]);
Run Code Online (Sandbox Code Playgroud)
控制器
$users = $this->Posts->Users->get(1, [
'contain' => ['Following.Posts']
]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
222 次 |
| 最近记录: |