Php 在多个相关表中执行满足条件的Laravel雄辩的“select”语句

Php 在多个相关表中执行满足条件的Laravel雄辩的“select”语句,php,mysql,sql,laravel,laravel-5,Php,Mysql,Sql,Laravel,Laravel 5,我有一个博客数据库模式,包括表、文章、类别和其他一些。对于posts表中的每个记录,都有一列post_category,其中包含categories表中记录的id。此外,还有标记字段post_active,分别表示类别表的cat_active,指示如果1-活动,如果0-非活动,是否可以读取post/类别 例如: 表员额: +---------+------------+----------------+---------------+-------------+ | post_id | post

我有一个博客数据库模式,包括表、文章、类别和其他一些。对于posts表中的每个记录,都有一列post_category,其中包含categories表中记录的id。此外,还有标记字段post_active,分别表示类别表的cat_active,指示如果1-活动,如果0-非活动,是否可以读取post/类别

例如:

表员额:

+---------+------------+----------------+---------------+-------------+
| 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\u active=1,但整个类别不是categories.cat\u active=0。我怎样才能选择所有活跃的帖子,这些帖子属于一个活跃的类别,并且很有说服力?香草SQL语句也可以工作,它可以很容易地转换为雄辩

非常感谢您的帮助

你可以使用where has来做你想做的事

后模型

那你就可以了

$posts = Post::where('post_active', '=', 1)
             ->whereHas('categories', function($q) {
                 $q->where('cat_active','=',1)
             })
             ->get();
这将只过滤具有活动类别的帖子。

category.php

Post.php

您的查询将是:

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

$posts = Post::where('post_active', '=', 1)
             ->whereHas('categories', function($q) {
                 $q->where('cat_active','=',1)
             })
             ->get();
class Category {
    public function posts() {
        return $this->hasMany(Post::class, 'post_category', 'cat_id')->active();
    }
    public function scopeActive() {
        return $query->where('cat_active', 1);
    }
}
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();