我在数据库中有一项研究要做。并非总是我会使用所有参数。用户可能想要研究名称,但不想搜索地址或相反。
我尝试使用高级位置甚至工会,但似乎都不起作用。他们都给了我一个SQL错误"一般错误:1221 UNION 和 ORDER BY 的错误使用"。
这是我尝试过的一段代码
$city_name = ($city_name != null) ? DB::table('cities')->where('name', 'LIKE', "%$city_name%") : DB::table('cities');
$state = ($state_id != '--') ? DB::table('cities')->where('state_id', '=', $state_id) : DB::table('cities');
$cities = DB::table('cities')->union($city_name)->union($state)->orderBy('name')->get();
但它给了我上面描述的错误。
我真正想做的是动态地选择我在查询中放入的参数,甚至"动态"组装它。有谁知道该怎么做?
如果我不能说清楚,请在评论中告诉我......
我认为你需要这样的想法:
$query = DB::table('cities');
if ($city_name != null)
{
$query->where('name', 'LIKE', "%$city_name%");
}
if ($state_id != '--')
{
$query->where('state_id', '=', $state_id);
}
$cities = $query->orderBy('name')->get();