Laravel 查询生成器获取自定义属性

Laravel query builder get custom attribute

我正在尝试获取自定义属性 (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();
}

Returns

[
 {
  "id": 1,
  "name": "User",
  "email": "user@test.com",
  "created_at": "2018-04-24 14:14:12",
  "role": {
   "name": "User"
  }
 }
]

所以问题是:有什么方法也可以获得 view_url 属性吗? (我在 with() 里面试过但是失败了)

我也可以 return 只有角色名称而不是整个对象吗,正如您在 "Return" 代码中看到的那样? (我想要这样的东西:"role":"User")。

(当然我尽量避免运行 raw sql)

谢谢!

你快完成了...

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') 预先加载。