【问题标题】:Multiple table inheritance in Laravel 5.2Laravel 5.2 中的多表继承
【发布时间】:2016-07-07 01:48:32
【问题描述】:

我正在使用 laravel 5.2。我的应用程序中有许多模型,即用户、律师、经理等。

我正在从基本用户模型扩展律师和经理模型。

    class LawyerController extends Controller
{
    //

    public function index()
    {
        $lawyer = Lawyer::findOrFail(1);
        return $lawyer->name;
    }
}

return 语句正在发送 null。

$lawyer->name 行不应该从基类中选择名称吗?那里有什么问题?是否可以以这种方式进行多表继承?

【问题讨论】:

  • 底层数据库是如何组织的?您是否有一个主用户表,然后为每个子类型单独的表?
  • 是的,我有一个主表和子类型的单独表

标签: eloquent laravel-5.2


【解决方案1】:

这就是我在 Eloquent 中制作多表继承的方式:

Morph over Model 继承,根据我对 Doctrine 的经验,多表中的模型继承被证明是非常低效的

这是我的 morphMap 配置

Relation::morphMap([
    2 => Flight::class,
    1 => Boat::class
], false);
/* The 'false' as second parameter is to indicate Eloquent that it has to use this map and nothing else, otherwise it will merge this map with what it gets from metadata and make a mess with that. I use this ints for the types because they are FKs of the table with all the types that I use to list in a Drop Down so the user can select what he wants to create */

class Sequence{
    /* Second parameter indicates the discriminator column name, that will be the column with the value indicating the type of the sublcass (1:B, 2:C) as mapped in morphMap and the third parameter indicates the key value of the sublcass (not FK_CONSTRAINT because it could be from Class B or C) */

    public function sequencable()
    {
        return $this->morphTo("sequencable","sequencable_type_id", "sequencable_id");
    }
}

Class Boat{
    public function sequence(){
        return $this->morphOne('Models\Sequence','sequencable');
    }
}

Class Flight{
    public function sequence(){
        return $this->morphOne('Models\Sequence','sequencable');
    }
}

现在要使用它,我写了如下内容:

$type = 2; //You get this from the request or whatever logic you have
$sequence= new Travel\Sequence()();
$model = $sequence->sequencable()->createModelByType($type);
$model->save();
$sequence->sequencable()->associate($model);
$sequence->save();

createModelByType($type) 方法很有用。

序列表如下所示:

//sequencable_type_id indicates the type of the sublcass
//sequencable_id indicates the type of the sublcass
{id,sequencable_type_id, sequencable_id}

子类是这样的

{id,column1, column2, etc...}

【讨论】:

  • 这是多态方法,不是多类表继承 (martinfowler.com/eaaCatalog/classTableInheritance.html)
  • 但是我应该在哪里定义这个Relation::morphMap
  • 任何地方,但你可以跳过它并使用字符串 sequencable_type 而不是 sequencable_type_id,Laravel 将使用类名作为 sequincable_type,Yosua 是对的,这是多态的而不是继承
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多