gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:59:07 25 4
gpt4 key购买 nike

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

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)

谢谢!

最佳答案

你几乎完成...

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')急切加载。

关于php - Laravel 查询生成器获取自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50704348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com