【发布时间】:2016-08-04 06:43:48
【问题描述】:
我有一个Posts 表,它有三个字段id、title、description。
我的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');
}
}
现在我想在有标签过滤器的地方获取帖子和分页,例如,我有两个标签 animals 和 news,其 ID 为 1 和 2。现在我想获取所有标签为1 & 2 & paginate 的帖子。这是我尝试过的
Post:: with('tags')->whereHas('tags', function($q) {
$q->whereIn('id', [1, 2]);
})->paginate();
但在这里我是whereIn,它返回的帖子有标签1 或2 或both。但我想要同时具有标签 id 1 和 2 的帖子。
我正在使用Laravel 5.2。
【问题讨论】:
标签: php laravel eloquent relationship