【问题标题】:Eloquent collections with a relation of another relation具有另一个关系的关系的雄辩集合
【发布时间】:2022-01-15 06:24:09
【问题描述】:

我有与 PostCategory 相关的 Post eloquent,我的收藏很好。

class Post extends Model
{

    public function post_categories()
    {
        return $this->belongsTo(PostCategory::class, 'category_id');
    }

    public function detail($slug_category, $slug)
    {
       $detail = Post::with('post_categories')
           ->whereHas('post_categories', function ($query) use ($slug_category){
            $query->where('category_slug', $slug_category);
         })->where('slug', $slug)
         ->first();
        return($detail);
    }

}

我有另一个类“玩家”,我需要一个包含所有用户帖子的集合,其中包含 PostCategory 类别关系。

class Players extends Model
{

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


    public function detail($slug_category, $slug_name)
    {

        $detail = Player::with('posts')
                        ->whereHas('players_info', function ($query) use ($slug_name){
                            $query->where('slug', $slug_name);
                        })
                        ->whereHas('player_categories', function ($query) use ($slug_category){
                            $query->where('category_slug', $slug_category);
                        })->first();

        return($detail);

    }

}

我读过一些关于“belongsToMany”和“withPivot”的内容,但我仍然对正确的方法感到困惑。

我能做些什么来解决这个问题?

谢谢!

【问题讨论】:

    标签: laravel eloquent relation


    【解决方案1】:

    我就用这个解决了。

    return $this->hasMany(Post::class)->with('post_categories');
    

    【讨论】:

    • with 没有定义任何关系,它只是在你的结果上加载一个关系。您通常可以使用 $player->posts()->first()->post_categories 懒惰地访问它
    猜你喜欢
    • 2020-09-08
    • 2014-08-27
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    相关资源
    最近更新 更多