我正在尝试为我正在创建的网站创建一个小功能,让您可以关注其他用户,然后您的仪表板会填满他们按照上传日期顺序上传的文件。(您可以将其与 youtube 进行比较。您订阅了一个频道,并在订阅页面上按您关注的人的日期顺序查看每个视频)。
这是我的模型结构(简化为仅显示所需的值以使其正常工作)。
跟随
- my_id(这是你的 id)
- user_id(这是您关注的用户的 ID)
用户
- id(用户标识)
文件
- user_id (上传文件的用户id)
- 路径(文件路径)
我现在尝试了很多方法来获取数据:
Follow::where('me_id', '=', Auth::user()->id)->get()->all()->files;
Follow::where('me_id', '=', Auth::user()->id)->get()->files;
唯一似乎有效的是(但这仅适用于 1 次关注):
Follow::where('me_id', '=', Auth::user()->id)->first()->files;
如果有人能看到我做错了什么,那就太棒了。
在我的Follow.php模型中,我将它连接成这样。
class Follow extends Model
{
protected $fillable = ['user_id', 'me_id'];
public function me()
{
return $this->belongsTo(User::class, 'id', 'me_id');
}
public function user()
{
return $this->belongsTo(User::class, 'id', 'user_id');
}
public function files()
{
return $this->hasManyThrough(
'App\File', //The model I'm trying to reach
'App\User', //The model I need to go through to reach the files
'id', //This is where I'm going wrong I think
'user_id', //Same here
'user_id', //Same here
'id' //Same here
);
}
}
编辑:
我让它在做 2 个单独的数据库调用。但这是否可能在一次通话中实现。请参阅下面的代码。
public function following(Request $request)
{
$follows = Follow::where('me_id', '=', Auth::user()->id)->get()->all();
$userIds = [];
foreach($follows as $key => $follow) {
$userIds[] = $follow->user_id;
}
$files = File::where('visible', '=', '1')->whereIn('user_id', $userIds)->orderBy('created_at', 'desc')->paginate(12)->onEachSide(3);
}