F
F
Fet2016-02-01 18:14:01
MySQL
Fet, 2016-02-01 18:14:01

How to make friends in Laravel 5 where()->orWhere and whereIn()?

I am fetching from a database. From the table I select posts of the user - public and private. Then I want to select posts from these posts only in certain categories.

$posts = Posts::where('status', 1)->orWhere(function($user_post){
                                    $user_post->where('status', 3)
                                                  ->where('public', 0);
                                    });
//какой-то код где получаем id категорий
$cats_id = [3, 7, 12 ,15];
$posts = $posts->whereIn('cat_id', $cats_id)->get();

Does not work. Still getting all posts, no category filter.
But, if you remove orWhere from the query, then whereIn () in the second query works.
I can get category id only after some manipulations. You won't be able to take them into the selection
right away. How to make friends where()->orWhere and whereIn()?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
ellrion, 2016-02-11
@halenharper

look, now your builder does the following `Condition_1 OR Condition_2 AND Condition 3`
You want it to be `(Condition_1 OR Condition_2) AND Condition 3`
"Parentheses" in the Laravel builder are added using an anonymous name.

$posts = Posts::where(function ($q) {
    $q->where('status', 1)
        ->orWhere(function($user_post){
            $user_post->where('status', 3)->where('public', 0);
        });
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question