我正在使用 laravel 8。我在存储库中有两个使用相同模型的不同函数。我在模型中有一个函数,该函数对于存储库中的每个函数都应该不同。 我怎么能说成模型不同的条件呢?我使用了属性和附加项目,但它无法正常工作。有办法处理吗?
在存储库中:
public function paginate(array $options = [])
{
$typeCode = $options['typeCode'] ?? null;
$user = Auth::user();
$is_admin = $user->isAdmin();
if(!$is_admin && $typeCode === null) {
throw BaseException::withMessages([
__('Gis::error.map_layer.not_allowed')
]);
}
$query = $this->model
->whereNull('ParentId')
->with(['descendants'])
->orderBy('Id', 'asc');
if ($typeCode !== null) {
$query->whereHas('MapLayerGroupType', function ($query) use ($typeCode) {
$query->where('Code', $typeCode);
});
}
$this->setQuery($query);
return parent::paginate($options);
}
public function mapGroupLayersList()
{
$query = $this->model
->with(['descendants'])
->whereNull('ParentId')
->orderBy('Id', 'asc');
$this->setQuery($query);
$result = parent::paginate();
return $result;
}
型号中:
public $timestamps = false;
protected $guarded = ['Id'];
protected $table = 'MapLayerGroup';
protected $appends = ['leaf', 'children'];
protected $hidden = ['descendants', 'mapLayers'];
public function parent()
{
return $this->belongsTo(MapLayerGroupModel::class, 'ParentId');
}
public function descendants()
{
return $this->hasMany(MapLayerGroupModel::class, 'ParentId')->orderBy('id', 'asc');
}
public function mapLayers()
{
return $this->hasMany(MapLayerModel::class, 'MapLayerGroupId', 'Id');
}
public function getChildrenAttribute()
{
if ('lablabla..' = true) {
return $this->descendants->toArray();
}
else {
return array_merge(
$this->descendants->toArray(),
$this->mapLayers->toArray()
);
}
}
public function getLeafAttribute()
{
return count($this->children) === 0; // If no children, it's a leaf (true), otherwise false
}
我使用静态属性来处理函数模型。
型号中:
public static $StaticProperty = false;
public function getChildrenAttribute()
{
if (self::$StaticProperty) {
return $this->descendants->toArray();
}
return array_merge(
$this->descendants->toArray(),
$this->mapLayers->toArray()
);
}
在存储库中:
public function paginate(array $options = [])
{
MapLayerGroupModel::$StaticProperty = false;
// Rest Codes
}
public function personalMapLayerGroupList()
{
MapLayerGroupModel::$StaticProperty = true;
// Rest Codes
}