Php 按模型自定义方法筛选集合
我正在为一个项目使用Laravel,我想根据模型中编写的自定义方法筛选集合: 控制器:Php 按模型自定义方法筛选集合,php,laravel,eloquent,model,Php,Laravel,Eloquent,Model,我正在为一个项目使用Laravel,我想根据模型中编写的自定义方法筛选集合: 控制器: $models= Produs::with('categorie') ->with('poza') ->with('element_extra.extras') ->get() ->where('id_stare', 1) ->where('categorie.id_restaurant', $idR
$models= Produs::with('categorie')
->with('poza')
->with('element_extra.extras')
->get()
->where('id_stare', 1)
->where('categorie.id_restaurant', $idRestaurant)
->groupBy('categorie.denumire');
$produse = $models->filter(function ($produs, $key) {
return $produs->isAvailable();
})->values();
型号:
class Produs extends Model
{
protected $table = "elemente";
public $timestamps = false;
public function isAvailable(){
if(...something....){
return false;
}else{
return true;
}
}
这就是我得到的:
BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::isAvailable does not exist.
::双冒号用于静态函数 尝试使用
public static function isAvailable(){}
您需要在方法中添加关键字
范围
public function scopeIsAvailable($query) {
return $query->where('active', true);
}
在那之后,就这样称呼它
$models= Produs::isAvailable()...
groupBy
返回集合中的集合,这就是为什么不能对其进行筛选。请添加任务的完整描述,以便找到更好的解决方案我有一些按类别分组的产品,但这些产品有一个计划id。在Isavailable函数中,我希望获得与该产品对应的计划,并计算if now()在计划中。If不是isavailable返回false,否则返回true。get()
应该在末尾。如果我使用static,我不能使用$this。If中的条件不是查询更复杂。