【问题标题】:Laravel : How to add conditional clause on a model having Many to Many model relationship?Laravel:如何在具有多对多模型关系的模型上添加条件子句?
【发布时间】:2021-10-25 21:03:20
【问题描述】:

我的User 模型上有这个方法。

public function reviews()
{
    return $this->belongsToMany(Review::class, 'review_user')->withTimestamps();
}

Review Model 处的倒数。


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

它们通过具有以下结构的数据透视表review_user 连接。

$table->id();
// User ID
$table->unsignedBigInteger('user_id')->nullable();
$table->foreign('user_id')
    ->references('id')
    ->on('users');

// Review ID
$table->unsignedBigInteger('review_id')->nullable();
$table->foreign('review_id')
    ->references('id')
    ->on('reviews');

$table->timestamps();

评论模型有一个布尔列status

我想要的是用户所有评论的状态为true

我已经能够使用Auth::user()->reviews()->get();实现users all reviews

如何添加可以按状态列过滤的 where 子句?

【问题讨论】:

    标签: laravel eloquent eloquent-relationship


    【解决方案1】:

    like 选项使用documentation

    像所有其他关系类型一样,您可以调用角色方法来继续将查询约束链接到关系上:

    $roles = App\User::find(1)->roles()->orderBy('name')->get();

    【讨论】:

      【解决方案2】:

      您可以通过使用 scope 或使用 Extra Where 子句定义相同的关系来实现此目的

      使用关系:

      public function Activereviews()
      {
          return $this->belongsToMany(Review::class, 'review_user')
           ->whereStatus(true)
           ->withTimestamps();
      }
      

      或使用范围:

      public function scopeActivereviews()
      {
          return $this->reviews()
           ->whereStatus(true);
      }
      

      现在你可以这样做了:

      Auth::user()->ActiveReviews()->get();
      

      希望对你有帮助。

      谢谢

      【讨论】:

        【解决方案3】:

        试试这样的代码,确实有效

        $reviews = auth()->user()->whereHas('reviews', function ($query) {
           return $query->where('status', '=', true);
        })->get();
        

        然后你检查the official documentation

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-07-10
          • 2016-07-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-05
          相关资源
          最近更新 更多