[英]Multiple models for one table Laravel
我有一个问题。 我尝试在 Laravel 5.6 中为一张表创建多个模型。 我有一张桌子,例如 Car,给他上课:
class Car extends Model {
$fillable = ['type'];
public function test(){ }
}
因此,字段类型是必需的。 例如模型车可以有多种类型(2-10..)。 根据类型,我应该在测试函数中运行不同的代码。 是的, if
构造,我可以做多个,但事实并非如此。 基于此,我想创建更多的类,这些类将从 Car 扩展并匹配每种类型。 例如:
class ElectricCar extends Car { $type = 'electric'; } ...
class SolarCar extends Car { $type = 'solar'; } ...
如果我要创建这个结构,我会遇到一些问题。
例如,id = 1 的记录是电动汽车。 如果调用Car::find(1)
会得到什么 是的,我会得到Car
类,但我需要ElectricCar
类。 我看到了https://github.com/Nanigans/single-table-inheritance ,但这不是一个好的解决方案。 它违反了 SOLID 规则之一,即在创建子类时我们不必更改父类。 那么我们可以根据SOLID
规则给我一个解决方案吗?
您可以通过使用范围来实现您所概述的内容。
创建一个新文件,类似于app/Scopes/SolarScope.php
并在里面放入以下代码:
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class SolarScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->where('type', 'Solar');
}
}
然后,在您的新模型内部,例如。 SolarCar.php
您需要指定用于该模型的表:
protected $table = 'cars';
然后您需要通过boot
功能指示该模型使用范围。
use App\Scopes\JobScope;
protected static function boot()
{
parent::boot();
static::addGlobalScope(new SolarScope);
// optionally instruct saving default type:
// static::saving(function ($car) {
// $car->type = 'Solar';
// });
}
这将确保每当引用 SolarCar 时,该类型都已在检索和可选的保存中限定范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.