【问题标题】:Laravel eloquent get all records wherehas all ids in many to many relationLaravel eloquent 获取所有记录,其中所有 id 具有多对多关系
【发布时间】:2016-08-04 06:43:48
【问题描述】:

我有一个Posts 表,它有三个字段idtitledescription

我的Post 模特

class Post extends Model
{
    use SoftDeletes;

    protected $fillable = ['title', 'description'];

    public function tags()
    {
        return $this->belongsToMany(Tag::class, 'post_tag');
    }
}

我的Tag 模特

class Tag extends Model
{
    use SoftDeletes;

    protected $fillable = ['name'];

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

现在我想在有标签过滤器的地方获取帖子和分页,例如,我有两个标签 animalsnews,其 ID 为 12。现在我想获取所有标签为1 & 2 & paginate 的帖子。这是我尝试过的

        Post:: with('tags')->whereHas('tags', function($q) {
            $q->whereIn('id', [1, 2]);
        })->paginate();

但在这里我是whereIn,它返回的帖子有标签12both。但我想要同时具有标签 id 1 和 2 的帖子。

我正在使用Laravel 5.2

【问题讨论】:

    标签: php laravel eloquent relationship


    【解决方案1】:

    然后,您必须遍历您的 id 列表才能添加该条件。例如:

    $query =  Post::with('tags');
    foreach ($ids as $id) {
        $query->whereHas('tags', function($q) use ($id) {
            $q->where('id', $id);
        });
    }
    $query->paginate();
    

    【讨论】:

    • 感谢@Joel,它对我有用,我会投赞成票,但当我在循环时,我会等待更好的答案。谢谢老兄。
    • 这很公平。很高兴它有帮助。 :)
    【解决方案2】:

    我一直在寻找同样的东西并受到this stackoverflow MySQL answer的启发,我最终得到了这个

    代码:

    Post:: with('tags')->whereHas('tags', function($q) {
        $idList = [1,2];
        $q->whereIn('id', $idList)
          ->havingRaw('COUNT(id) = ?', [count($idList)])
    })->paginate();
    

    因为我想我可能会在一些地方使用它,所以我将它变成了一个你可以view here 的特征。如果您在 Post 类中包含该特征,则可以像下面这样使用。

    代码:

    Post::with('tags')->whereHasRelationIds('tags', [1,2])->paginate();
    

    【讨论】:

      【解决方案3】:

      我不认为有一个内置的方法可以解决这个问题,但我建议将 foreach 循环放在 whereHas 方法中,只是为了简洁。

      $query = Post::with('tags')->wherehas('tags', function ($q) use ($ids) {
          foreach ($ids as $id) {
              $q->where('id', $id);
          }
      })->paginate(10);
      

      【讨论】:

      • 你试过这个@alexleonard 吗?我之前试过这个,但没有用。
      • 这永远不会起作用,因为 'id' 不能同时是两个值。您的子查询将返回类似 SELECT * FROM tags WHERE id = 1 and id = 2;
      猜你喜欢
      • 2017-12-19
      • 2021-03-23
      • 1970-01-01
      • 2020-01-06
      • 2020-09-10
      • 2020-11-26
      • 1970-01-01
      • 2017-04-22
      • 2017-07-25
      相关资源
      最近更新 更多