gpt4 book ai didi

Laravel - 获取与 "whereHas"的嵌套关系

转载 作者:行者123 更新时间:2023-12-05 00:45:34 28 4
gpt4 key购买 nike

我有三个型号 Period , Post , User :

  • periodpostsperiod_posts 上有 M:N 关系
  • postsuserviews 上有 M:N 关系

  • 期间型号:
    class Period extends Model
    {

    public $timestamps=false;

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

    岗位型号:
    class Post extends Model
    {
    public function periods()
    {
    return $this->belongsToMany(Period::class);
    }


    public function views()
    {
    return $this->belongsToMany(User::class, 'views')
    ->withTimestamps();
    }
    }

    用户型号:
    class User extends Authenticatable
    {
    use Notifiable;



    public function views()
    {
    return $this->belongsToMany(Post::class, 'views')
    ->withTimestamps();
    }
    }

    View 表:
    id user_id post_id
    我需要得到所有 periods与其 posts哪里 auth user没看过(按浏览量关系)

    我试图这样做,但没有奏效:
        $period = Period::whereHas('posts.views', function ($users) {
    $users->where('user_id', auth()->Id());
    })->get();

    最佳答案

    似乎你的模型有点“凌乱”,你可以用 Eloquent 得到你想要的东西,但你必须将逻辑分成几个部分。

    例子:

    // Get all user seen posts #1
    $seenPosts = Auth::user()->views()->pluck('id');

    // Get all user unseen posts with its period inside the collection #2
    $posts = Post::whereNotIn('id',$seenPosts)->with('periods')->get();

    关于Laravel - 获取与 "whereHas"的嵌套关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56929854/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com