1

我正在尝试为我正在创建的网站创建一个小功能,让您可以关注其他用户,然后您的仪表板会填满他们按照上传日期顺序上传的文件。(您可以将其与 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);
    }
4

2 回答 2

1

您的模型定义没问题,因为您可以使用以下方式获取文件:

Follow::where('me_id', '=', Auth::user()->id)->first()->files;  

你的错误

以下代码返回一个laravel 集合

Follow::where('me_id', '=', Auth::user()->id)->get()

以下代码返回一个数组:

Follow::where('me_id', '=', Auth::user()->id)->get()->all()

并且filesFollow模型的动态属性(不是集合也不是数组)。所以这不会像你期望的那样工作。

您正确的解决方案

您应该使用雄辩的关系功能:

Follow::with('files')->where('me_id', '=', Auth::user()->id)->get()

这将返回一个Follow包含所有它们各自的集合files。喜欢:

[
    'my_id' -> 1,
    'user_id' -> 1,
    'files' -> [
        'user_id' -> 1,
        'path' -> '/foo/bar'
    ]
]
于 2018-12-22T21:00:47.533 回答
0

我认为您可以分两步完成此操作。

  1. 获取用户关注的用户
  2. 从具有第一个查询的 id 的用户那里获取文件
于 2018-12-22T20:51:01.857 回答