【问题标题】:Laravel query builder get custom attributeLaravel 查询生成器获取自定义属性
【发布时间】:2018-11-15 04:36:23
【问题描述】:

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

谢谢!

【问题讨论】:

  • 你看过 $appends 属性了吗?受保护的 $appends = ['view_url'];在您的用户模型中。
  • 你的意思是像名字旁边的('role:view_url')?

标签: php laravel eloquent laravel-5.5


【解决方案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') 急切加载。

【讨论】:

  • 不敢相信我就快到了(坚持了好几个小时..)非常感谢凯特尔!
  • 不客气! Laravel Docs 非常好,但没有解释所有细节。 Laracasts 有更多详细信息,请访问 Laracasts 网站,你会发现更多关于 Laravel 的信息。
猜你喜欢
  • 2016-04-27
  • 2016-11-07
  • 1970-01-01
  • 2017-05-09
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
  • 2017-05-22
  • 1970-01-01
相关资源
最近更新 更多