本文介绍在 laravel 中不使用循环的前提下,将 `with()` 预加载的关联模型(如 `role`)字段(如 `role_name`、`role_category`)直接合并到主模型(如 `user`)的 json/数组输出中,实现结构扁平化。核心方案是结合访问器(accessors)与 `$appends` 或运行时 `append()`。
在 Laravel 中,当使用 ->with('role') 加载关联关系后,role 默认以嵌套对象形式存在于结果中(如 "role": { "role_name": "Admin" }),但实际 API 或前端常需扁平结构(如直接 "role_name": "Admin")。手动 foreach 提取字段不仅冗余,还违背 Eloquent 的声明式设计哲学。正确做法是利用 Laravel 的 访问器(Accessors) 与 序列化追加机制。
在 App\Models\User 模型中添加以下代码:
// app/Models/User.php
protected $appends = ['role_name', 'role_category'];
public function getRoleNameAttribute()
{
return $this->relationLoaded('role') ? $this->role->role_name : null;
}
public function getRoleCategoryAttribute()
{
return $this->relationLoa
ded('role') ? $this->role->role_category : null;
}✅ 关键点说明:
若该扁平化行为仅在特定接口需要(而非全局),可避免污染模型定义,改用链式 append():
$users = User::where('active', 1)
->whereHas('role', function ($query) use ($column, $role) {
$query->where('role_'.$column, $role);
})
->with('role:id,role_name,role_category')
->orderBy('users.id')
->get([
'id',
'email',
'phone_number',
'id_role',
'firstname',
'lastname',
'verified',
'active',
'id_configuration',
'external_service_id',
])
->map(function ($user) {
return $user->append(['role_name', 'role_category'])->toArray();
});⚠️ 注意:append() 必须在 toArray() 之前调用;若使用 ->get()->toArray(),请确保 append() 在集合每个模型上执行(如上例的 map)。
经上述任一方案处理后,$users->toArray() 将输出完全符合预期的扁平结构:
[
{
"id": 968,
"email": "[email protected]",
"phone_number": "123",
"id_role": 4,
"firstname": "Name",
"lastname": "TEST User",
"verified": 0,
"active": 1,
"id_configuration": 1,
"external_service_id": 123,
"role_name": "Admin",
"role_category": "Company"
}
]——简洁、可维护、零循环,真正发挥 Laravel Eloquent 的声明式优势。