如何解决getAttribute 方法未使用查询构建器调用 laravel
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
我尝试了什么:
User::select('first_name','last_name')
->with([
'fullName' => function($query){
$query->select(DB::raw("CONCAT(first_name,' ',last_name) AS full_name"));
}
])
->where('user_id',$id)
->where('is_deleted',0)
->first();
我尝试的另一种方式:
User::select(DB::raw("CONCAT(first_name,last_name) AS full_name"))
->with([
'fullName' => function($query){
$query->select('firstname','lastname');
}
])
->where('user_id',0)
->first();
但没有任何东西叫 get<>Attribute
名字。
解决方法
访问者不是关系。试试
$user = User::where('user_id',$id)->first();
dd($user->full_name);
,
这些是 Laravel 中的魔法方法。
这意味着以下列方式处理这些:
-
getFullNameAttribute
去掉了get
和attribute
;只离开FullName
。 - 然后将其转换为
snake_case
,从而得到full_name
。 - 然后将此值添加到
attributes
数组中,该数组可在视图中访问,就像常规属性一样。
实际上,这将为您留下以下代码。
$user = User::first();
echo $user->full_name;
这假设您采用了以下第一种方法:
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
如果您想以 $user->fullname
的身份访问该属性,则需要采用以下方法:
public function getFullnameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
请注意,我们现在有 Fullname
,带有小写的 n
。
所有魔法 getter(和 setter)都是这种情况,它们将根据它们的 snake_case
转换为 PascalCase
。
有趣的是,您可以执行以下操作,它会起作用:
getfull_nameAttribute()
{
// ...
}
Relevant framework code。
Laravel 只关心 get
和 Attribute
书挡。
这不是,accessors 是如何工作的。您通过使用 with()
将其视为关系。只需从您的查询中删除 with()
,在查询用户后,您就可以访问 $user->full_name;
在模型中定义方法
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
然后在查询中,例如,如果您正在获取一条记录,则
$res= \App\Models\User::first();
dd($res->fullName);
这意味着您的属性是 FullName
然后访问时第一个字母变为 small letter
当你尝试
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
然后在模型内部你也需要添加这个
protected $appends = ['full_name'];
这是你遗漏的然后它会起作用 参考链接 https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。