簡體   English   中英

Laravel雄辯地得到所有記錄,其中所有ID都存在多對多關系

[英]Laravel eloquent get all records wherehas all ids in many to many relation

我有一個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 現在我想獲得所有標簽為12paginate帖子。 這是我試過的

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

但在這里,因為我在whereIn返回帖子有標簽12both 但我希望發布標簽為id 1和2的帖子。

我正在使用Laravel 5.2

然后,您必須遍歷您的ID列表以添加該條件。 例如:

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

我一直在尋找相同的東西,並受到這個stackoverflow MySQL答案的啟發,我最終得到了這個

碼:

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

因為我認為我可以在一些地方使用它,我已經把它變成了一個你可以在這里查看的特性。 如果您在Post類中包含該特征,則可以使用如下所示。

碼:

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

我不認為有一個內置的方法,但我建議將foreach循環放在whereHas方法中,只是為了整潔。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM