【问题标题】:Laravel QueryBuilder conditionLaravel 查询生成器条件
【发布时间】:2021-09-07 22:33:29
【问题描述】:

在 Laravel 中,我想构建如下查询。

有一个status column,值应该是01

还有另一列,device_idsarray

现在,在查询中,我想在device_ids 上应用不同的逻辑,当状态为0 且状态为1

有人可以建议我最好的方法吗?

$builder->where('status','0')->whereJsonDoesntContain('device_ids', $imei_id->id)

$builder->where('status','1')->whereJsonContains('device_ids', $imei_id->id)

如何将两者结合起来?

$all_applications = $builder->where('status', $model->status) 
->when($status, function ($query) { 
    Log::error("One"); 
    return $query->whereJsonContains('device_ids', 107); }, 
  function($query) { 
   Log::error("Zero"); return $query
  ->whereJsonDoesntContain('device_ids', 107); }); 

如果我使用 $model->status ,它会给我类似“未定义变量:模型”的错误

【问题讨论】:

  • 你能展示一下到目前为止你尝试了什么吗?
  • 你的问题不清楚,你的意思是“应用不同的逻辑”?你想获取什么信息,在什么条件下?
  • $builder->orderBy('weight', 'desc')->where('progress','complete')->whereJsonDoesntContain('device_ids', $imei_id->id);
  • 这里如果status = 1,我要申请,whereJsonContains
  • 我更新了问题

标签: sql laravel eloquent


【解决方案1】:

你必须使用when

$result = YourModel::where('status', $status)
    ->when($status, function ($query) {
        return $query->whereJsonContains('device_ids', $imei_id->id);
    }, function ($query) {
        return $query->whereJsonDoesntContain('device_ids', $imei_id->id);
    });

【讨论】:

  • 这看起来不错,但是,我想要 0 和 1 状态输入。$result = YourModel::where('status', $status) ->when($status == 1, function ( $query) { return $query->whereJsonContains('device_ids', $imei_id->id); }, function ($query) { return $query->whereJsonDoesntContain('device_ids', $imei_id->id); }) ;
  • 我们可以这样做吗?
  • 目前正在这样做,请阅读随附的文档。如果值(在这种情况下为$status)是真实值,则将运行第一个函数,在您的情况下为1,并且第二个函数仅在该值是假的情况下运行,0 在您的情况下.
  • 但我不想手动传递 $status 值,表中有一个名为 status 的列。如果 status 的值为 1,那么当 function 和 0 时,应该调用 else 语句。
  • 但这没问题,使用模型变量并访问该部分...您必须保留要使用的代码。如果要使用列,请使用 $model->status 之类的模型,即基本 PHP/Laravel。
猜你喜欢
  • 2017-03-30
  • 2014-08-20
  • 1970-01-01
  • 2019-11-27
  • 2015-12-13
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多