我正在使用laravel 5.2。我的应用程序中有许多模型,即用户,律师,经理等
我正在从基本用户模型扩展Lawyer和Manager模型。
class LawyerController extends Controller
{
//
public function index()
{
$lawyer = Lawyer::findOrFail(1);
return $lawyer->name;
}
}
return语句发送空。
行$lawyer->name
不应该从基类中选择名称吗?有什么问题?是否可以以这种方式进行多表继承?
答案 0 :(得分:0)
这就是我在Eloquent中进行多重继承工作的方法:
对模型继承进行变形,根据我对Doctrine的经验,多表中的模型继承被证明是非常低效的
这是我的morphMap配置
@echo off
setlocal enabledelayedexpansion
set X=3
set FOLDER_PATH=.
pushd %FOLDER_PATH%
for %%f in (*) do if %%f neq %~nx0 (
set "filename=%%~nf"
set "filename=!filename:~%X%!"
ren "%%f" "!filename!%%~xf"
)
popd
现在使用它,我写了类似的东西:
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');
}
}
方法 createModelByType($ type)是一个有用的东西。
Sequence表看起来像这样:
$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();
子类看起来像这样
//sequencable_type_id indicates the type of the sublcass
//sequencable_id indicates the type of the sublcass
{id,sequencable_type_id, sequencable_id}