Laravel 5.2 How to use "OR LIKE" in the "AND" condition

I am new to laravel and I have to face some problems in getting records. The table structures are as follows:

main_categories
------------------
id      name
1       NNN
2       PPP

categories
-----------------------------------
id      name    main_category_id
-----------------------------------
1       abc         1
2       xyz         2
3       lmn         1

services
------------------
id  categories
------------------
1   a:2:{i:0;s:1:"1";i:1;s:2:"3";}
2   a:1:{i:0;s:3:"2";}
3   a:1:{i:0;s:3:"3";}
4   a:2:{i:0;s:1:"1";i:1;s:3:"3";}

Categories stored in services are in serialized form.

In the form, I have drop-down lists according to the main category, and each drop-down list has subcategories.

These messages are in this format:

Array ([0] => array ([0] => 1, [1] => 3,), [1] => array ([0] => 2))

: 5 , - , "" "" "" .

SQL :

SELECT * FROM `services` WHERE (`categories` LIKE '%"1"%' OR `categories` LIKE '%"3"%') AND (`categories` LIKE '%"2"%')

Laravel :

$categories = [1,3];

\DB::table ('services')
->where(function($q) use ($categories) {
    foreach($categories as $category) {
        $q->where('services.categories', 'like', '%"'.DB::raw($category).'"%');
    }
})

. Laravel.

+4
2

, , , . , :

$categories = [1,3];

\DB::table ('services')
->where(function($q) use ($categories) {
    foreach($categories as $key => $category) {
        if ($key == 0) {
            $q->where('services.categories', 'like', '%"'.DB::raw($category).'"%');
        } else {
            $q->orWhere('services.categories', 'like', '%"'.DB::raw($category).'"%');
        }
    }
});

, ...

+1

, orWhere():

orWhere('name', 'like', 'John')
0

Source: https://habr.com/ru/post/1651793/


All Articles