jeudi 5 juillet 2018

Perform Laravel Eloquent 'select' statement meeting conditions in multiple related tables

I have a blog database schema with tables posts, categories and a few more. For every record in posts table there is a column post_category containing the id of a record in categories table. Also there are flag fields post_active, respectively cat_active (for categories table) indicating if the post/category is available to be read or not (if 1 - active, if 0 - inactive).

For example:

Table "posts":

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

Table "categories":

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

Currently, I'm using Eloquent's where() clause to select all active posts from posts table:

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

But there might be a situation in which a post is active (posts.post_active = 1), but the whole category is not (categories.cat_active = 0). How can I select all active posts, which belong to an active category with Eloquent? Vanilla SQL statement also works, it can easily be converted to Eloquent.

Any help is greatly appreciated!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire