Laravel-使用“ whereHas”

时间:2019-07-08 07:04:46

标签: laravel eloquent relationship

我有三个模型PeriodPostUser

  • 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();
  }
}

观看次数表:

id    user_id    post_id

我需要获取所有periods及其posts,其中auth user尚未看到(按视图关系)

我尝试执行此操作,但这没用:

    $period = Period::whereHas('posts.views', function ($users) {
        $users->where('user_id', auth()->Id());
    })->get();

4 个答案:

答案 0 :(得分:4)

似乎您的模型有点“混乱”,您可以通过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(); 

答案 1 :(得分:1)

您可以使用我在计算机上测试过的whereDoesntHave,它运行良好:

$post_ids = Post::whereDoesntHave('views', function($q){
    $q->where('user_id',Auth::id());
})->get()->pluck('id');
$periods = Period::whereHas('posts', function($q) use($post_ids){
    $q->whereIn('post_id',$post_ids);
})->get();
dd($periods->pluck('id'));

答案 2 :(得分:0)

假设您有一个用于Views表的模型,则可以使用View模型来查找所有看不见的帖子。

View::where('user_id', '!=', Auth::user()->id)->groupBy('post_id')->whereHas('posts')->pluck('post_id');

答案 3 :(得分:0)

我的解决方案只对一个查询执行相同操作:

Period::query()
      ->whereHas('posts', function ($query) {
        $query->whereHas('views', function ($query) {
          $query->where('users.id', '=', auth()->Id());
        }, '=', 0);
    });