2015-12-25 5 views
0

Я использую laravel 5.2. У меня есть много моделей в моем приложении, то есть пользователь, юрист, менеджер и т. Д.Множественное наследование таблиц в Laravel 5.2

Я расширяю модель Lawyer and Manager от базовой модели пользователя.

class LawyerController extends Controller 
{ 
    // 

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

Оператор возврата отправляет null.

Не следует ли линия $lawyer->name выбрать имя из базового класса? Что там не так? И можно ли таким образом наследовать несколько таблиц?

+0

Как организован основной базы данных? У вас есть таблица основных пользователей, а затем отдельные таблицы для каждого подтипа? – alexw

+0

Да, у меня есть главная таблица и отдельные таблицы для подтипа –

ответ

0

Это, как я сделал многотабличное Наследование работы в красноречиве:

Morph над моделью наследование, наследование модели в многотабличном оказалось очень неэффективным основано на моем опыте с доктриной

Это мой 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...} 
+0

, это полиморфный подход, а не наследование многоклассовой таблицы (https://www.martinfowler.com/eaaCatalog/classTableInheritance.html) –

+0

, но где я должен определить этот ' связь :: morphMap'? –

+0

В любом месте, но вы можете пропустить это и использовать строку sequencable_type вместо sequencable_type_id, Laravel будет использовать имя класса как sequencable_type, а Yosua прав, это полиморфное и не наследование –

Смежные вопросы