【发布时间】:2018-09-25 05:21:36
【问题描述】:
我遇到了 Laravel 中的 hasManyThrough 函数的问题。
我的目标是获取登录用户关注的用户显示帖子的提要。我尝试通过以下方式实现:
- 在User.php中,获取登录用户的ID
- 将用户的 id 与 Follow.php 中名为 user_id 的列匹配
- 从Follow.php的行中获取target_id
- 从 Follow.php 中获取 user_id 与 target_ids 匹配的帖子
我通过用户关注的人正确检索数据。但是,数据中返回的 user_id 是登录用户,而不是帖子的作者。为什么?
用户.php
public function feed() {
return $this->hasManyThrough(
'App\Post',
'App\Follow',
'user_id',
'user_id',
'id',
'target_id'
)
->with('user')
->orderBy('id', 'DESC');
}
Post.php
public function user() {
return $this->belongsTo('App\User');
}
从控制器调用
$posts = Auth::user()->feed;
【问题讨论】:
标签: php mysql laravel has-many-through