一张桌子的多个模型Laravel

问题描述 投票:0回答:2

我有一个问题。我尝试在Laravel 5.6中为一个表创建多个模型。我有一张桌子,例如汽车,为他上课:

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规则给我什么解决方案?

php laravel single-table-inheritance
2个回答
0
投票

也许使用laravel scope?您可以在汽车模型中调用这样类型的汽车:

public function scopeElectricCar($query)
{
    return $query->where('type', 'electric');
}

然后您可以像这样呼叫电动车:

Car::electricCar();

0
投票

您可以通过使用范围实现概述的内容。

创建一个新文件,类似于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时,该类型就已经在检索和保存中都处于范围内。

© www.soinside.com 2019 - 2024. All rights reserved.