有没有一种优雅的方式来嵌套转换器以供关系使用?我正在寻找构建一个允许集合有条件地包含关系模型的 REST 接口。到目前为止,我取得了一定的成功,但在涉及到变形金刚时,它似乎有点崩溃(我承认我对 Laravel 5.1 和 Dingo 有点陌生)。我希望尽可能保持 DRY,这样如果将来关系或属性发生变化,它就很容易改变。
例如,一个用户可能会收到一条或多条消息的简单场景(用户有很多收到的消息)我可以在 UserTransformer 中执行以下操作:
<?php
namespace App\Transformers;
use App\Models\User;
use League\Fractal;
class UserTransformer extends Fractal\TransformerAbstract
{
public function transform(User $user)
{
// Transform the basic model
$returnUser = [
'id' => (int) $user->id,
'email' => $user->email,
'role' => $user->role,
'status' => $user->status,
'links' => [
[
'rel' => 'self',
'uri' => '/users/'.$user->id
]
]
];
// Transform relationships, but only if they exist and are requested
if (isset($user->receivedMessages))
{
$returnUser['received_messages'] = [];
foreach ($user->receivedMessages as $msg)
{
$returnUser['received_messages'][] = [
'id' => $msg->id,
'read' => $msg->read,
'content' => $msg->content
];
}
}
return $returnUser;
}
}
在这种情况下,我想将 MesagesTransformer 嵌套/应用到相关接收到的消息以进行输出格式化,以便所有 REST 输出在所有关系中保持一致。这可能吗?谢谢!