【问题标题】:Laravel Query in if else converting to common queryLaravel Query in if else 转换为普通查询
【发布时间】:2022-11-23 17:16:22
【问题描述】:

这是我的代码,我想将此查询转换为通用查询

 if ($limit == 0) {
   $response = WebhookErrorNotification::where('is_error', true)->orderByDesc('id')->get();
   } else {
  $response = WebhookErrorNotification::where('is_error', true)->orderByDesc('id')->limit($limit)->get();
            }

【问题讨论】:

  • 常见查询是什么意思?

标签: php laravel eloquent laravel-8


【解决方案1】:

您可以将查询保存在 if/else 语句上方的变量中。所以这样的事情会起作用。现在,如果这不是您正在寻找的答案,请说明您所说的常见查询的含义!

$query = WebhookErrorNotification::where('is_error', true)->orderByDesc('id');
if ($limit == 0) {
  $response = $query->get();
} else {
  $response = $query->limit($limit)->get();
}

【讨论】:

    【解决方案2】:

    你可以这样做

    $response = WebhookErrorNotification::where('is_error', true)
        ->when($limit !== 0, function ($query) use ($limit) {
            $query->limit($limit);
        })->orderByDesc('id')->get();
    

    【讨论】:

      猜你喜欢
      • 2018-02-21
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      • 2020-01-18
      • 1970-01-01
      • 2019-04-09
      • 2014-04-10
      相关资源
      最近更新 更多