我有一个Profiles模型,它有一些关系(belongsTo,HasManyThought)。
我想一个接一个地根据几个参数进行过滤。
例如:
个人资料模型:
class Perfis extends Model
{
protected $guarded = [];
public function usuario(){
return $this->belongsTo(User::class, 'user_id');
}
public function enderecos(){
return $this->belongsTo (Enderecos::class);
}
public function categorias(){
return $this->belongsToMany (
Categorias::class,
'perfis_categorias'
);
}
// Filtros
public function scopeFilter($query, $filtros){
return $filtros->apply($query);
}
}
配置文件CONTROLLER
公共职能指数(PerfisFiltros $ filtros,Request $ request) { $ perfis = Perfis :: filter($ filtros) - > get();
return view('frontal.perfis.index', [
'perfis' => $perfis,
]);
}
我的过滤器
public function apply($builder)
{
if(! $this->request->has('_token')) return $builder;
if($this->request->has('_token')){
return $builder
->when($this->request->has('fCat'), function ($fCategoria) {
$fCategoria->whereHas('categorias', function ($fCategoriaHas){
$fCategoriaHas->where('categorias_id', $this->request->fCat);
});
})
->when($this->request->has('fEstado'), function ($fEstado){
$fEstado->whereHas('enderecos', function ($fEstadoHas){
$fEstadoHas->where('estados_id', $this->request->fEstado);
});
});
}
}
答案 0 :(得分:0)
我无法绕过你想要做的事情......但我马上就知道你回来的时间太早......在这里
if(! $this->request->has('_token')) return $builder;
并且
if($this->request->has('_token')){
return $builder
你没有给这些人一个机会跑:
->when($this->request->has('fCat'), function ($fCategoria) {
$fCategoria->whereHas('categorias', function ($fCategoriaHas){
$fCategoriaHas->where('categorias_id', $this->request->fCat);
});
})
->when($this->request->has('fEstado'), function ($fEstado){
$fEstado->whereHas('enderecos', function ($fEstadoHas){
$fEstadoHas->where('estados_id', $this->request->fEstado);
});
});
答案 1 :(得分:0)
通过更改我的查询,我能够解决我的需求。
我的过滤器
if(!empty($this->request->fEstado)){
$builder
->whereHas('enderecos', function ($fEstadoHas){
$fEstadoHas->where('estados_id', $this->request->fEstado);
});
}
if(!empty($this->request->fCat)){
$builder->whereHas('categorias', function ($fCat){
$fCat->where('categorias_id', $this->request->fCat);
});
}
if(!empty($this->request->fChave)){
$builder->whereHas('anuncios', function ($fChave){
$fChave->where('corpo', 'like', '%'.$this->request->fChave.'%')
->orWhere('titulo', 'like', '%'.$this->request->fChave.'%');
});
}
return $builder;