在多个相关表中执行Laravel Eloquent'select'语句满足条件

时间:2018-07-05 18:15:54

标签: php mysql sql laravel laravel-5

我有一个博客数据库架构,其中包含表postscategories等。对于posts表中的每个记录,都有一列post_category,其中包含categories表中记录的ID。还分别有标记字段post_activecat_active(对于categories表),指示帖子/类别是否可以读取(如果为1,则为活动;如果为0,则为非活跃)

例如:

表格“帖子”:

+---------+------------+----------------+---------------+-------------+
| post_id | post_title |  post_content  | post_category | post_active |
+---------+------------+----------------+---------------+-------------+
|    1    | Lorem..... | ipsum dolor... |  1            | 1           |
+---------+------------+----------------+---------------+-------------+

表格“类别”:

+--------+----------+------------+
| cat_id | cat_name | cat_active |
+--------+----------+------------+
| 1      | Category |  1         |
+--------+----------+------------+

当前,我正在使用Eloquent的where()子句从posts表中选择所有活动帖子:

$posts = Post::where('post_active', '=', 1)->get();

但是可能存在这样的情况,即帖子处于活动状态(posts.post_active = 1),但整个类别都不是(categories.cat_active = 0)。如何选择Eloquent所属的所有活跃帖子? Vanilla SQL语句也可以工作,可以轻松地转换为Eloquent。

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您可以使用whereHas做您想做的事。

发布模型

class Post ...
...
    public function categories()
    {
        return $this->belongsTo(Category::class, 'post_category', 'cat_id');
    }

那你就可以做

$posts = Post::where('post_active', '=', 1)
             ->whereHas('categories', function($q) {
                 $q->where('cat_active','=',1)
             })
             ->get();

这将仅过滤具有有效类别的帖子。

答案 1 :(得分:0)

Category.php

class Category {
    public function posts() {
        return $this->hasMany(Post::class, 'post_category', 'cat_id')->active();
    }
    public function scopeActive() {
        return $query->where('cat_active', 1);
    }
}

Post.php

class Post {
    public function category() {
        return $this->belongsTo(Category::class, 'post_category', 'cat_id')->active()
    }

    public function scopeActive() {
        return $query->where('post_active', 1);
    }
}

您的查询将是:

$categories = Category::active()->with('posts')->get();

$posts = Post::active()->has('category')->get();