如何在 laravel 查询生成器中获取后备行?
How to get fallback row in laravel query builder?
我有一个格式如下的数据库table。
| from_zone | from_type | to_zone | to_type | client_id | rate |
|-----------|-----------|---------|----------|-----------|------|
| north | national | north | national | 1 | 12 |
| north | national | north | metro | 1 | 15 |
| north | national | north | metro | null | 21 |
型号 - Drate,table - drate
要获取客户 ID 1 的费率,我们有以下查询
$drate=Drate::where('from_zone','north')->where('from_type','national')
->where('to_zone','north')->where('to_type','metro')
->where('client_id',1)->get();
dd($drate->rate);
// output is 15
如果没有提供客户端 ID(即 21),如何获得回退率?如果客户 ID 提供的费率是 15.
欢迎来到 SO。
一种可能的解决方案是有条件地添加 where('client_id',1) 子句。
$drate = Drate::where('from_zone','north')
->where('from_type','national')
->where('to_zone','north')
->where('to_type','metro');
if( client id provided condition is true ) // pseudo-code
$drate->where('client_id',1);
$drate = $drate->get();
编辑:
请记住,这将导致多个匹配项。您的示例中的两行都将匹配。
当 client_id = null 未提供 whereNull('client_id')[=27 时,您可以 if/else 仅查询 return =].
if( client id provided condition is true ) // pseudo-code
$drate->where('client_id',1);
else
$drate->whereNull('client_id');
然后,它还可以匹配具有相同条件的其他条目(例如,客户端为空的多行)。
决定当 client_id = null 时结果应该是什么,以及如果需要多个结果时的排序方式。
例如,如果您要求 client_id = null 应该只有 return 1 个结果并且该结果应该是最高比率,您可以结合 orderBy('rate', 'desc') 用 first() 而不是 get();
我有一个格式如下的数据库table。
| from_zone | from_type | to_zone | to_type | client_id | rate |
|-----------|-----------|---------|----------|-----------|------|
| north | national | north | national | 1 | 12 |
| north | national | north | metro | 1 | 15 |
| north | national | north | metro | null | 21 |
型号 - Drate,table - drate
要获取客户 ID 1 的费率,我们有以下查询
$drate=Drate::where('from_zone','north')->where('from_type','national')
->where('to_zone','north')->where('to_type','metro')
->where('client_id',1)->get();
dd($drate->rate);
// output is 15
如果没有提供客户端 ID(即 21),如何获得回退率?如果客户 ID 提供的费率是 15.
欢迎来到 SO。
一种可能的解决方案是有条件地添加 where('client_id',1) 子句。
$drate = Drate::where('from_zone','north')
->where('from_type','national')
->where('to_zone','north')
->where('to_type','metro');
if( client id provided condition is true ) // pseudo-code
$drate->where('client_id',1);
$drate = $drate->get();
编辑: 请记住,这将导致多个匹配项。您的示例中的两行都将匹配。
当 client_id = null 未提供 whereNull('client_id')[=27 时,您可以 if/else 仅查询 return =].
if( client id provided condition is true ) // pseudo-code
$drate->where('client_id',1);
else
$drate->whereNull('client_id');
然后,它还可以匹配具有相同条件的其他条目(例如,客户端为空的多行)。
决定当 client_id = null 时结果应该是什么,以及如果需要多个结果时的排序方式。
例如,如果您要求 client_id = null 应该只有 return 1 个结果并且该结果应该是最高比率,您可以结合 orderBy('rate', 'desc') 用 first() 而不是 get();