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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?