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?

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();