为了提高性能,我尝试只创建一个数据库查询,并在视图刀片中显示多个foreach。为了产生这个结果,我的方法是使用查询生成器和selectRaw创建过滤器。
我现在的代码是:
$totals = DB::table('product')->select('productName','sellingPrice','productSpecification')
->selectRaw("(case where categoryId = '177' then 1 end) as computers")
->selectRaw("(case where categoryId = '31388' then 1 end) as cameras")
->selectRaw("(case where categoryId = '9355' then 1 end) as mobiles")
->get();
}其想法是在刀片视图中以以下方式使用selectraw:
@foreach ($totals->computers as $productcomputers)
@foreach ($totals->cameras as $productcameras)
@foreach ($totals->mobiles as $productmobiles)我尝试过这种方法,但我收到了错误:
SQLSTATE42000:语法错误或访问冲突: 1064您的SQL语法出现了错误;请检查与MySQL服务器版本对应的手册,以获得正确的语法,以便在“where categoryId = '177‘然后1结束)作为计算机使用。
有什么建议是用laravel产生一个多前额的查询,还是解决当前的方法?
brgds,
发布于 2019-07-31 08:45:32
尝尝这个
$totals = DB::table('product')->select('productName','sellingPrice','productSpecification')
->whereIn('categoryId', [177, 31388, 9355])
->selectRaw("(case when categoryId = '177' then 1 end) as computers")
->selectRaw("(case when categoryId = '31388' then 1 end) as cameras")
->selectRaw("(case when categoryId = '9355' then 1 end) as mobiles")
->get();
$data = collect();
$data->computers = $totals->where('computers', '!=', null);
$data->cameras = $totals->where('cameras', '!=', null);
$data->mobiles = $totals->where('mobiles', '!=', null);现在在刀片视图中使用
@foreach ($data->computers as $productcomputers)
@foreach ($data->cameras as $productcameras)
@foreach ($data->mobiles as $productmobiles)希望这能帮到你。
发布于 2019-07-31 07:31:29
将case where替换为case when。您可以在此链接查看文档。
https://stackoverflow.com/questions/57285409
复制相似问题