laravel - 检索属于 laravel 类别列表的帖子

标签 laravel eloquent

我需要您的帮助来找到创建此查询的解决方案。假设我有 2 个表:帖子和类别,以及一个数据透视表:category_post。

posts: id, title, ...

类别:id、category_name、...

category_post: post_id, category_id

现在,我要检索我想要的类别:

$categories = Category::whereIn('id', $array)->lists('id');

在这个查询之后,我得到了一个类别 ID 列表,我只想检索属于这些类别的帖子。不仅是属于一个或另一个类别的帖子,还有属于所有这些类别的帖子。

我希望我解释得很好。 问候

最佳答案

您可以为枢轴类注册一个belongTo 关系。 (前提是 category_idpost_id 是外键。)

class CategoryPost extends Eloquent {

    protected $table = 'category_post';

    public function posts() {
        return $this->belongsTo('posts');
    }

    public function categories() {
        return $this->belongsTo('categories');
    }
}

现在,你可以调用

CategoryPost::with('posts')->whereIn('category_id', $categories)->groupBy('post_id')->get();

关于laravel - 检索属于 laravel 类别列表的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35441265/

相关文章:

Laravel 在 Eloquent 中使用 with() 方法时出错

mysql - Eloquent Join,多个where查询,把AND改成OR

php - 与 4 个表的关系 [Laravel 5]

php - 更改 ENUM 列并将值添加到 Laravel 中的该列

mysql - 与 Laravel/Eloquent 的复杂关系

php - 路由的 laravel file_get_contents 没有响应

带有 Laravel 的 PHP 应用服务器

mysql - DB where 在两个日期列之间

laravel 无法为序列化准备路线...。使用闭包

php - 如何使用 Eloquent 从嵌套关系中加载特定字段?