我相信这里最好的解决方案(至少对于数据库大小)是简单地更改readable_type
为ENUM('Lion\Company', 'Lion\People')
.
话虽这么说,如果你真的想在 Laravel 端处理这个问题,你必须创建从Illuminate\Database\Eloquent\Relations\Morph*
¹扩展的新类并覆盖它们的构造函数²以便只获得破折号后的最后一个值, on $morphClass
。像这样的东西:
<?php
use \Illuminate\Database\Eloquent\Model;
use \Illuminate\Database\Eloquent\Builder;
class MyMorphOne extends \Illuminate\Database\Eloquent\Relations\MorphOne {
public function __construct(Builder $query, Model $parent, $type, $id) {
parent::__construct($query, $parent, $type, $id);
$this->morphClass = substr($this->morphClass, strrpos($this->morphClass, '\\') + 1);
}
}
然后,扩展您自己的模型或基础模型,覆盖morphOne
,morphMany
和morphToMany
方法以使用您的新扩展类。像这样的东西:
<?php
class People extends Eloquent {
// ...
public function morphOne($related, $name, $type = null, $id = null) {
$instance = new $related;
list($type, $id) = $this->getMorphs($name, $type, $id);
$table = $instance->getTable();
return new MyMorphOne($instance->newQuery(), $this, $table.'.'.$type, $table.'.'.$id);
}
}
*
= One
,Many
和ToMany
- 这实际上是从
MorphOneOrMany
onMorphOne
和继承的MorphMany
。