【问题标题】:Does Laravel Eloquent 'where' guarantee order?Laravel Eloquent 'where' 保证订单吗?
【发布时间】:2023-04-08 02:16:01
【问题描述】:

例如,这样做:

Model::where('role', 'all')->orWhere('role','user')->first();

总是首先获取角色为“all”的模型,因为 where() 的声明早于 orWhere()?

或者我不应该相信它并总是检查 if 吗?

$foo = new Model;
$bar = $foo->where('role', 'all')->first();
if(empty($bar)){
    $bar = $foo->where('role','user')->first();
}

或者也许是更好的解决方案?

【问题讨论】:

    标签: sql laravel eloquent


    【解决方案1】:

    不会的,和 Laravel 没有任何关系,SQL 就是这样工作的。

    查询生成器将生成以下 SQL 语句:

    SELECT * FROM Model WHERE `role` = 'all' OR `role` = 'user' LIMIT 1;
    

    您获取行的顺序将是它们在Model 表中的顺序。如果要对行进行排序,则必须对查询应用顺序,例如:

    Model::where('role', 'all')
        ->orWhere('role','user')
        ->orderByRaw('CASE role WHEN \'all\' THEN 1 ELSE 2 END DESC')
        ->first();
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      Model::whereIn('role', ['all', 'user'])->get();
      

      如果您想订购结果并只获得第一个结果,您可以像这样指定顺序:

       Model::whereIn('role', ['all', 'user'])->orderBy('some_column', 'ASC')->first();
      

      当然,你也可以这样:

      Model::where('role', 'all')->orWhere('role','user')->orderBy('some_column', 'ASC')->first();
      

      【讨论】:

        猜你喜欢
        • 2014-08-14
        • 1970-01-01
        • 2018-02-21
        • 2017-08-30
        • 2020-07-09
        • 1970-01-01
        • 2021-09-08
        • 2014-06-13
        • 1970-01-01
        相关资源
        最近更新 更多