我正在尝试获取自定义属性(https://laravel.com/docs/5.5/eloquent-mutators#defining-an-accessor) 来自查询。
现在我有:
user.php的
public function getViewUrlAttribute()
{
return route('admin.users.view', ['id' => $this->id]);
}
public function role()
{
return $this->belongsTo('App\Role')->withDefault([
'name' => 'User'
]);
}
UserController.php
public function dataTable(Request $request)
{
$length = $request->has('length') ? $request->input('length') : 10;
$orderDirection = $request->input('orderDirection');
$searchValue = $request->input('search');
$users = User::select('id', 'name', 'email', 'created_at')->with('role:name')->limit($length);
if ($request->has('orderBy')) {
if ($request->has('orderDirection')) {
$users = $users->orderBy($request->input('orderBy'), $request->input('orderDirection') > 0 ? 'asc' : 'desc');
} else {
$users = $users->orderBy($request->input('orderBy'), 'desc');
}
}
return $users->get();
}
返回
[
{
"id": 1,
"name": "User",
"email": "user@test.com",
"created_at": "2018-04-24 14:14:12",
"role": {
"name": "User"
}
}
]
所以问题是:有什么方法可以获得view_url属性? (我在with()中尝试了但是它失败了)
我也可以只返回角色名称而不是整个对象,如“返回”代码中所示? (我想要的是:“角色”:“用户”)。
(我当然试图避免运行原始的sql)
谢谢!
答案 0 :(得分:1)
你差不多完成了......
1-要添加自定义属性,您需要将其附加到具有$appends
属性的模型中:
protected $appends = ['view_url'];
并定义属性方法:
public function getViewUrlAttribute()
{
return route('admin.users.view', ['id' => $this->id]);
}
2-要从另一个相关模型向模型添加属性,我认为您应该尝试:
// to add them as attribute automatically
protected $appends = ['view_url', 'role_name'];
// to hide attributes or relations from json/array
protected $hidden = ['role']; // hide the role relation
public function getRoleNameAttribute()
{
// if relation is not loaded yet, load it first in case you don't use eager loading
if ( ! array_key_exists('role', $this->relations))
$this->load('role');
$role = $this->getRelation('role');
// then return the name directly
return $role->name;
}
那么您可能不需要->with('role')
急切加载事件。