如果我的组件与同一模型有关系,我该怎么办,所以,如果没有这个模型,我想取消返回这个组件?



我至少有8个组件与课程模型有相同的关系,如果教程隐藏,我想取消返回该组件

我试图在全局范围内进行,但仍然需要在所有这些组件的模型whereHaswith中进行。我如何在哪个模型的范围内进行这些操作?我不想在所有组件中重复这些关系,也许在全球范围内重复一次,或者类似的东西

注:我使用的是laravel 5.8我必须在所有组件中重复这一点,比如材料

$callQuery=function($q) use ($request){
if(!$request->user()->can('course/show-hidden-courses'))
$q->where('show',1);
};
// $material = $materials_query->with(['lesson','course.attachment'])->whereIn('lesson_id',$lessons);
$material = $materials_query->whereHas('course',$callQuery)->with(['lesson','course' => $callQuery]);

我不确定,我是否理解你的问题。但是,如果你想在任何地方使用相同的where。你可以在你的模型中创建一个范围,基本上就像:

public function scopeCourse($query){
$query->whereHas('course', function ($q){
$q->where('show', 1);
});
}

Andy如果你喜欢这个过滤器,你可以查询如下:

$materials_query->course()->with([...]);

此外,如果你想在任何地方强制执行它,你可以在中创建一个全局作用域;AppModelScope,代码如下:

<?php
namespace AppModelScope;
use IlluminateDatabaseEloquentScope;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentBuilder;
class CourseScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param  IlluminateDatabaseEloquentBuilder  $builder
* @param  IlluminateDatabaseEloquentModel  $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
return $builder->whereHas('course', function ($q){
$q->where('show', 1);
});
}
}

然后在你的模型中,你可以:

protected static function boot()
{
parent::boot();
static::addGlobalScope(new CourseScope);
}

然后,你可以像这样写你的查询:

$materials_query->with([...]);

作用域将自动强制执行,而无需实际调用作用域,在我们的案例中为course()。有时你不需要强制执行,所以你可以打电话给:

$materials_query->withoutGlobalScope();

最新更新