是否有一种优雅的方式来嵌套变形金刚以供关系使用?我正在构建一个REST接口,允许集合有条件地包含关系模型。到目前为止,我已经取得了一定的成功,但在变形金刚方面似乎有所分析(我承认我对Laravel 5.1和Dingo有点新意)。我希望尽可能保持干燥,这样如果将来关系或属性发生变化,很容易改变。
例如,用户可能收到一条或多条消息的简单场景(用户已收到许多消息)我可以在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输出在所有关系中保持一致。这可能吗?谢谢!