Laravel where - 如何在条件下引用相同的模态?

我想在where()条件(Laravel 5.8)中使用一些自定义逻辑,例如下面的。该where()参数将根据变量而变化。下面的代码不起作用,但让您了解我想要实现的目标。我怎样才能得到想要的结果?


\App\Model::where(function ($query) use ($quantity, $price_criteria) {

    if ($model->threshold_1 <= $quantity) {

        $compare = $model->price_1

    } elseif ($model->threshold_2 <= $quantity) {

        $compare = $model->price_2

    } else {

        $compare = $model->price_3

    } 

    $query->where($compare, "<=", $price_criteria)

}->orWhere...


慕盖茨4494581
浏览 242回答 3
3回答

开心每一天1111

如果我正确理解您的问题,您可以使用whereRaw()查询来构建您的条件,或者使用where()/构建单独的查询条件whereOr()。使用whereRaw(),\App\Model::whereRaw("price_1 <= ? AND threshold_1 <= ?", [$price_criteria, $quantity])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ->orWhereRaw("price_2 <= ? AND threshold_2 <= ?", [$price_criteria, $quantity])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ->orWhereRaw("price_3 <= ?", [$price_criteria]);或者使用 Eloquent,\App\Model::where(function($query) use ($quantity, $price_criteria) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$query->where("price_1", "<=", $price_criteria)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;->where("threshold_1", "<=", $quantity);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;})->orWhere(function($query) use ($quantity, $price_criteria) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$query->where("price_2", "<=", $price_criteria)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;->where("threshold_2", "<=", $quantity);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;})->orWhere(function($query) use ($quantity, $price_criteria) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$query->where("price_3", "<=", $price_criteria)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;});

哆啦的时光机

您应该$model像$quantity和一样传递参数$price_criteria(并添加一些标点符号:)):\App\Model::where(function ($query) use ($quantity, $price_criteria, $model) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ($model->threshold_1 <= $quantity) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $compare = $model->price_1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } elseif ($model->threshold_2 <= $quantity) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $compare = $model->price_2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $compare = $model->price_3;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $query->where($compare, "<=", $price_criteria);&nbsp; &nbsp; &nbsp; &nbsp; })->orWhere();希望有帮助。

繁星点点滴滴

简单地说,你不能。您在这里所做的只是构建一个返回数据的 SQL 查询,并且在获取数据之前您无法访问该数据。为了以这种方式实际过滤数据,您需要首先检索所有数据并过滤集合。
打开App,查看更多内容
随时随地看视频慕课网APP