我目前正在尝试清理我的 Laravel 模型中的代码,目前我在每个模型中都有大量与本地作用域相关的代码重复。每个模型都有很多相似的相关列,我正在弄清楚如何将这些范围放在一个地方,但仍然能够传递 $table
变量,以便它可以动态使用。
例如我目前有几个模型
public function scopeName($query, $name)
{
return $query->where($this->table.'name', $name);
}
public function scopeStatus($query, $status)
{
return $query->where($this->table.'.status', $status);
}
我想采用这些通用范围并将它们放在一个类中,我可以在其中将表传递给它,然后我可以消除代码重复。无法找到与扩展父模型类似的任何内容。我也知道全局范围,但这仍然会产生类似的问题,我在每个模型中键入 static::addGlobalScope(new StatusScope)
。
非常感谢任何帮助。
在这里使用特征会被认为是一个糟糕的选择吗?
最佳答案
Trait 在这里比继承更好,阅读更多:https://en.wikipedia.org/wiki/Composition_over_inheritance
你可以为它创建一个新的特征:
trait CommonScopesTrait
{
public function scopeName($query, $name)
{
return $query->where($this->table.'name', $name);
}
public function scopeStatus($query, $status)
{
return $query->where($this->table.'.status', $status);
}
}
并在您的模型中使用它:
class YourModel extends Model
{
use CommonScopesTrait;
}
关于php - 在 Laravel 中向父模型添加作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44277856/