see*_*iue 6 php laravel eloquent laravel-5.5
我试图从查询中获取自定义属性( https://laravel.com/docs/5.5/eloquent-mutators#defining-an-accessor )。
现在我有:
用户.php
public function getViewUrlAttribute()
{
return route('admin.users.view', ['id' => $this->id]);
}
public function role()
{
return $this->belongsTo('App\Role')->withDefault([
'name' => 'User'
]);
}
Run Code Online (Sandbox Code Playgroud)
用户控制器.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();
}
Run Code Online (Sandbox Code Playgroud)
退货
[
{
"id": 1,
"name": "User",
"email": "user@test.com",
"created_at": "2018-04-24 14:14:12",
"role": {
"name": "User"
}
}
]
Run Code Online (Sandbox Code Playgroud)
所以问题是:有什么方法也可以获取 view_url 属性吗?(我在 with() 内部尝试过,但失败了)
另外,我可以只返回角色名称而不是整个对象,如您在“返回”代码中看到的那样吗?(我想要类似:“角色”:“用户”)。
(当然我试图避免运行原始sql)
谢谢!
你几乎完成...
1-要添加自定义属性,您需要将其附加到带有属性的模型上$appends:
protected $appends = ['view_url'];
Run Code Online (Sandbox Code Playgroud)
并定义你的属性方法:
public function getViewUrlAttribute()
{
return route('admin.users.view', ['id' => $this->id]);
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
那么您可能不需要->with('role')急切加载。
| 归档时间: |
|
| 查看次数: |
12637 次 |
| 最近记录: |