微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – Laravel eloquent获取所有记录,其中包含许多关系中的所有ID

我有一个帖子表,它有三个字段id,标题,描述.

我的帖子模型

class Post extends Model
{
    use SoftDeletes;

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

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

我的标签模型

class Tag extends Model
{
    use SoftDeletes;

    protected $fillable = ['name'];

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

现在我想得到帖子&我有标签过滤器的分页符,例如我有两个标签动物& id为1&的新闻2.现在我想获得所有标记为1&的帖子. 2&分页.这是我试过的

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

在这里,因为我在哪里返回帖子有标签1或2或两者.但我想要帖子谁同时标记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();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐