doujiao2000 2018-01-03 15:10
浏览 33
已采纳

Laravel 5变量构造查询字符串Eloquent

I am trying to take JSON sent to my Laravel server and return the results of an Eloquent query string which is itself constructed based on the JSON that is being sent. I plan to chain together multiple where/whereHas statements to achieve this, but so far I am stuck on the first and wondering if this is possible.

Code:

if(isset($settings->new)){
$assetQuery = "where('created_at','>',".Carbon::now()->subMonths(1).")";
}
if(isset($settings->long)){
$assetQuery = "where('lengthD','Long')";
}
if(isset($settings->short)){
$assetQuery = "where('lengthD','Short')";
}
if(!isset($settings->new)&&!isset($settings->long)&&!isset($settings->short)){
$assetQuery = "where('id','>',0)";
}
$batch = MyModel::whereHas('asset',function ($query) use ($assetQuery){return $query->$assetQuery;})
->orderBy('id', 'desc')->take(20)->get();

$settings is a json_decode representation of my JSON. It will only have one instruction where in comes to the $assetQuery. As you can see, if it fails to have any of these instructions it will pick all of them (where('id','>',0)).

My issue is I can't seem to append the $assetQuery string to the $batch Eloquent line. How can I do this so I can string together variable queries?

I did see this: Laravel Advanced Wheres how to pass variable into function?

But in that case the variable was being used in one very small section of the query, not for the whole query string. Maybe I need to move my conditionals within the function ($query) function?

  • 写回答

1条回答 默认 最新

  • doulin6448 2018-01-03 15:29
    关注

    I'm not 100% sure on exactly what you're asking, but I think the following will work for you.

    $batch = MyModel::whereHas('asset', function ($query) use ($settings){
        if(isset($settings->new)){
            $query->where('created_at','>',Carbon::now()->subMonths(1));
        }
        if(isset($settings->long)){
            $query->where('lengthD','Long');
        }
        if(isset($settings->short)){
            $query->where('lengthD','Short');
        }
        if(!isset($settings->new)&&!isset($settings->long)&&!isset($settings->short)){
            $query->where('id','>',0);
        }
    })->orderBy('id', 'desc')->take(20)->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器