[英]Multiple models for one table Laravel
I have one problem.我有一个问题。 I try to create multiple models for one table in Laravel 5.6.
我尝试在 Laravel 5.6 中为一张表创建多个模型。 I have a table for example Car, class for him:
我有一张桌子,例如 Car,给他上课:
class Car extends Model {
$fillable = ['type'];
public function test(){ }
}
So, the field type is required.因此,字段类型是必需的。 Eg model car can have multiple types (2-10..).
例如模型车可以有多种类型(2-10..)。 Depending on the type I should run difference code in test function.
根据类型,我应该在测试函数中运行不同的代码。 Yes, i can do multiple
if
conctructions, but it's not true.是的,
if
构造,我可以做多个,但事实并非如此。 Based on this I would like to create more classes that will be extended from Car and will to match to each of the types.基于此,我想创建更多的类,这些类将从 Car 扩展并匹配每种类型。 For example:
例如:
class ElectricCar extends Car { $type = 'electric'; } ...
class SolarCar extends Car { $type = 'solar'; } ...
If I will create this structure than I get a few problems.如果我要创建这个结构,我会遇到一些问题。
For example record for id = 1 is Electric car.例如,id = 1 的记录是电动汽车。 What will I get if call
Car::find(1)
Yes, I will get Car
class, but I need ElectricCar
class.如果调用
Car::find(1)
会得到什么 是的,我会得到Car
类,但我需要ElectricCar
类。 I saw https://github.com/Nanigans/single-table-inheritance , but it's not a good solution.我看到了https://github.com/Nanigans/single-table-inheritance ,但这不是一个好的解决方案。 it violates one of the SOLID rules, where we haven't to change parent class when creating child class.
它违反了 SOLID 规则之一,即在创建子类时我们不必更改父类。 So what is a solution we can give me based on
SOLID
rules?那么我们可以根据
SOLID
规则给我一个解决方案吗?
You can achieve what you have outlined by using scopes.您可以通过使用范围来实现您所概述的内容。
Create a new file, something like app/Scopes/SolarScope.php
and inside, put the following code:创建一个新文件,类似于
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');
}
}
Then, inside of your new model, eg.然后,在您的新模型内部,例如。
SolarCar.php
you need to specify the table to use for that model: SolarCar.php
您需要指定用于该模型的表:
protected $table = 'cars';
and then you need to instruct that Model to use the scope via the boot
function.然后您需要通过
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';
// });
}
This will make sure whenever a SolarCar is referenced, the type is already scoped in both in retrieval and optionally in saving.这将确保每当引用 SolarCar 时,该类型都已在检索和可选的保存中限定范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.