我是laravel的新手,我在获取记录方面遇到了一些问题.表结构如下:
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";}
存储在服务中的类别是序列化形式.
在一个表格中,我根据主要类别有下拉列表,每个下拉列表都有子类别.
帖子数据采用以下格式:
阵列(
[0] =>阵列(
[0] => 1,
[1] => 3,
)
[1] =>阵列(
[0] => 2
)
)
流程ID如下:按主要类别划分5个下拉菜单,选项是他们的子类别,我想在子类别或相同的主要类别和“AND”条件之间加上“OR”条件和另一组“OR”其他主要类别的条件.
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中正确完成.
解决方法
代码有点难看,但可能适用于您的情况.所以,试试这个:
$categories = [1,3];
\DB::table ('services') ->where(function($q) use ($categories) { foreach($categories as $key => $category) { if ($key == 0) { $q->where('services.categories','%"'.DB::raw($category).'"%'); } else { $q->orWhere('services.categories','%"'.DB::raw($category).'"%'); } } });
希望这可以帮助…