Laravel的多态关联允许一个模型在单个关联中属于多个其他模型,比如评论模型可以同时关联文章和用户,这种灵活的关联方式在很多业务场景中非常实用。但在实际开发中,我们经常需要将多态关联的数据转换为特定格式的数组,适配接口返回或者数据处理的场景。

多态关联基础回顾
首先我们简单回顾下多态关联的基本定义,以评论关联文章和用户为例,评论模型的关联定义如下:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentRelationsMorphTo;
class Comment extends Model
{
/**
* 定义多态关联,评论可以属于文章或者用户
*/
public function commentable(): MorphTo
{
return $this->morphTo();
}
}
文章模型和用户模型的关联定义分别如下:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentRelationsMorphMany;
class Post extends Model
{
/**
* 文章有多个评论
*/
public function comments(): MorphMany
{
return $this->morphMany(Comment::class, 'commentable');
}
}
class User extends Model
{
/**
* 用户有多个评论
*/
public function comments(): MorphMany
{
return $this->morphMany(Comment::class, 'commentable');
}
}
默认数组转换的问题
当我们直接调用模型的toArray()方法时,多态关联返回的数据会包含默认的关联模型信息,比如下面的代码:
<?php
$comment = Comment::with('commentable')->first();
$array = $comment->toArray();
print_r($array);
默认输出的数组会包含commentable_type和commentable_id字段,同时关联加载的commentable对象会直接序列化为数组,很多时候我们不需要这些冗余字段,或者需要自定义关联数据的输出格式。
基础转换技巧:使用append和访问器
我们可以通过定义访问器和append属性,自定义多态关联数据的数组输出。首先在Comment模型中定义访问器获取关联模型的自定义数据:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentRelationsMorphTo;
class Comment extends Model
{
// 追加到数组的自定义字段
protected $appends = ['commentable_info'];
public function commentable(): MorphTo
{
return $this->morphTo();
}
/**
* 获取自定义的多态关联信息
*/
public function getCommentableInfoAttribute()
{
if (!$this->commentable) {
return null;
}
// 根据关联模型类型返回不同格式的数据
$type = $this->commentable_type;
$data = $this->commentable->toArray();
return [
'type' => class_basename($type),
'id' => $data['id'],
'name' => $data['name'] ?? $data['title'] ?? '',
];
}
}
这样当我们调用$comment->toArray()时,数组就会包含commentable_info字段,并且隐藏默认的commentable_type和commentable_id字段,可以在模型的$hidden属性中配置:
protected $hidden = ['commentable_type', 'commentable_id', 'commentable'];
进阶技巧:自定义序列化逻辑
如果需要更复杂的转换逻辑,可以重写模型的toArray方法,或者定义专门的转换方法。比如我们需要处理嵌套的多态关联,或者根据业务场景过滤字段:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentRelationsMorphTo;
class Comment extends Model
{
public function commentable(): MorphTo
{
return $this->morphTo();
}
/**
* 自定义多态关联数组转换方法
*/
public function toCustomArray(): array
{
$base = $this->toArray();
// 移除不需要的字段
unset($base['commentable_type'], $base['commentable_id']);
// 处理多态关联数据
if ($this->relationLoaded('commentable') && $this->commentable) {
$commentable = $this->commentable;
$base['commentable'] = [
'type' => class_basename($commentable),
'id' => $commentable->id,
];
// 根据不同类型追加不同字段
if ($commentable instanceof Post) {
$base['commentable']['title'] = $commentable->title;
$base['commentable']['summary'] = mb_substr($commentable->content, 0, 50);
} elseif ($commentable instanceof User) {
$base['commentable']['nickname'] = $commentable->nickname;
$base['commentable']['avatar'] = $commentable->avatar;
}
} else {
$base['commentable'] = null;
}
return $base;
}
}
使用时直接调用$comment->toCustomArray()就可以得到符合需求的数组格式。
批量转换集合数据
如果需要转换多个评论的集合数据,可以使用集合的map方法批量处理:
<?php
$comments = Comment::with('commentable')->get();
$commentArrays = $comments->map(function ($comment) {
return $comment->toCustomArray();
})->toArray();
print_r($commentArrays);
注意事项
- 转换数组时如果需要关联数据,一定要先使用
with预加载关联,避免N+1查询问题 - 自定义访问器时,注意
append属性的字段名要和访问器方法名对应,比如commentable_info对应getCommentableInfoAttribute方法 - 如果多态关联模型有自定义的序列化规则,需要注意避免规则冲突,优先保证业务需要的字段输出