【发布时间】:2020-10-03 18:57:03
【问题描述】:
我有一个雄辩的查询,我运行了两次,但感觉可以运行一次。
如果存在,我想返回第一个 where 语句的值,否则检查第二个 where 语句,它是查询中的默认值。
这就是我目前正在做的事情:
$details = Telco::select('telcos.id AS telco_id', 'telcos.name AS telco_name')
->leftJoin('telco_prefixs', 'telco_prefixs.telco_id', '=', 'telcos.id')
->where('telco_prefixs.prefix', '=', $phone_number) // check if ndc exists
->first();
if ($details){
return $details;
}
return Telco::select('telcos.id AS telco_id', 'telcos.name AS telco_name')
->leftJoin('telco_prefixs', 'telco_prefixs.telco_id', '=', 'telcos.id')
->where('telcos.name', '=', 'Default') //default channel
->first();
我觉得这可以组合成如下内容:
但是,这会因为继续执行 OrWhere 子句而失败。
Telco::select('telcos.id AS telco_id', 'telcos.name AS telco_name')
->leftJoin('telco_prefixs', 'telco_prefixs.telco_id', '=', 'telcos.id')
->where('telco_prefixs.prefix', '=', $phone_number) // if ndc exists
->Orwhere('telcos.name', '=', 'Default') //default channel
->first();
有人帮忙。谢谢
【问题讨论】:
-
是的,已经有 orWhere(小写 o 字母 W 大写)laravel.com/docs/7.x/eloquent-relationships#querying-relations
-
你能分享两个表结构以及
leftJoin是否必要(以及为什么)