正如 OP 在他的 cmets 中所说:数据库设计已经设置好,因此 Laravel 的 Polymorphic Relationships 似乎不是这里的选项。
我喜欢 Chris Neal 的回答,因为我最近不得不做一些类似的事情(编写我自己的数据库驱动程序来支持 Eloquent 用于 dbase/DBF 文件)并且在 Laravel 的内部获得了很多经验雄辩的 ORM。
我在其中添加了我的个人风格,以使代码更具动态性,同时保持每个模型的显式映射。
我快速测试的支持的功能:
-
Animal::find(1) 按照您的问题进行操作
-
Animal::all() 也可以
-
Animal::where(['type' => 'dog'])->get() 将返回 AnimalDog-objects 作为一个集合
- 每个使用此特征的 eloquent 类的动态对象映射
- 回退到
Animal-model,以防未配置映射(或数据库中出现新映射)
缺点:
- 它正在完全重写模型的内部
newInstance() 和newFromBuilder()(复制和粘贴)。这意味着,如果框架对此成员函数有任何更新,您将需要手动采用代码。
我希望它对您有所帮助,并且我愿意为您的方案中的任何建议、问题和其他用例提供帮助。以下是它的用例和示例:
class Animal extends Model
{
use MorphTrait; // You'll find the trait in the very end of this answer
protected $morphKey = 'type'; // This is your column inside the database
protected $morphMap = [ // This is the value-to-class mapping
'dog' => AnimalDog::class,
'cat' => AnimalCat::class,
];
}
class AnimalCat extends Animal {}
class AnimalDog extends Animal {}
这是一个如何使用它的例子,下面是它的相应结果:
$cat = Animal::find(1);
$dog = Animal::find(2);
$new = Animal::find(3);
$all = Animal::all();
echo sprintf('ID: %s - Type: %s - Class: %s - Data: %s', $cat->id, $cat->type, get_class($cat), $cat, json_encode($cat->toArray())) . PHP_EOL;
echo sprintf('ID: %s - Type: %s - Class: %s - Data: %s', $dog->id, $dog->type, get_class($dog), $dog, json_encode($dog->toArray())) . PHP_EOL;
echo sprintf('ID: %s - Type: %s - Class: %s - Data: %s', $new->id, $new->type, get_class($new), $new, json_encode($new->toArray())) . PHP_EOL;
dd($all);
结果如下:
ID: 1 - Type: cat - Class: App\AnimalCat - Data: {"id":1,"type":"cat"}
ID: 2 - Type: dog - Class: App\AnimalDog - Data: {"id":2,"type":"dog"}
ID: 3 - Type: new-animal - Class: App\Animal - Data: {"id":3,"type":"new-animal"}
// Illuminate\Database\Eloquent\Collection {#1418
// #items: array:2 [
// 0 => App\AnimalCat {#1419
// 1 => App\AnimalDog {#1422
// 2 => App\Animal {#1425
如果你想使用MorphTrait,这里当然是它的完整代码:
<?php namespace App;
trait MorphTrait
{
public function newInstance($attributes = [], $exists = false)
{
// This method just provides a convenient way for us to generate fresh model
// instances of this current model. It is particularly useful during the
// hydration of new objects via the Eloquent query builder instances.
if (isset($attributes['force_class_morph'])) {
$class = $attributes['force_class_morph'];
$model = new $class((array)$attributes);
} else {
$model = new static((array)$attributes);
}
$model->exists = $exists;
$model->setConnection(
$this->getConnectionName()
);
$model->setTable($this->getTable());
return $model;
}
/**
* Create a new model instance that is existing.
*
* @param array $attributes
* @param string|null $connection
* @return static
*/
public function newFromBuilder($attributes = [], $connection = null)
{
$newInstance = [];
if ($this->isValidMorphConfiguration($attributes)) {
$newInstance = [
'force_class_morph' => $this->morphMap[$attributes->{$this->morphKey}],
];
}
$model = $this->newInstance($newInstance, true);
$model->setRawAttributes((array)$attributes, true);
$model->setConnection($connection ?: $this->getConnectionName());
$model->fireModelEvent('retrieved', false);
return $model;
}
private function isValidMorphConfiguration($attributes): bool
{
if (!isset($this->morphKey) || empty($this->morphMap)) {
return false;
}
if (!array_key_exists($this->morphKey, (array)$attributes)) {
return false;
}
return array_key_exists($attributes->{$this->morphKey}, $this->morphMap);
}
}