如何调用模型 Collection laravel 上的函数

How to call a function on model Collection laravel

在我post之前我已经搜索了很多答案但没有结果请原谅我的英语不是那么好

我的 Laravel 应用包含:

用户模型

public function Follow()
{
    return $this->belongsToMany(Page::class,"follows","user_id","page_id");
}

页面模型

public function Posts()
{
    return $this->hasMany(Post::class);
}

Post 型号

public function Page()
{
    return $this->belongsTo(Page::class);
}

在 homeController 中,我的索引方法应该 return 用户关注页面的 post

$user->follow()->get(); 

这 return 只编辑了 Pages 集合,我无法获取 Posts 或访问任何 我需要访问 post 及其属性,如果可能的话,我还需要计算 post 的点赞次数。

非常感谢。

您正在使用follow() return 页面的功能!!检查您的 return 声明

应该是:

public function Follow() { return $this->belongsToMany(Follow::class,"follows","user_id","page_id"); }

经过万亿次尝试,我找到了答案

    public function index()
{
    $user = Auth::User();
    $posts = [];

    foreach ($user->follow as $key => $page) 
    {
        foreach ($page->posts as $k => $post)
        {
            array_push($posts, $post);
        }

    }
    //return $posts;
    return view('home', compact('posts'));
}

我还不能访问点赞数,但我会尝试 with('') 方法 我会更新任何进一步的信息