getAttribute 方法未使用查询生成器调用 laravel

getAttribute method is not calling laravel using query builder

我尝试了多种方法来调用模型中的以下方法

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', $id)
        ->where('is_deleted', 0)
        ->first();

但没有任何东西在调用 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

访问器不是关系。尝试

$user = User::where('user_id', $id)->first();


dd($user->full_name);

当你尝试时

public function getFullNameAttribute()
{
   return "{$this->first_name} {$this->last_name}";
}

然后在模型内部你也需要添加这个

protected $appends = ['full_name'];

这个你错过了然后它会起作用 参考 link https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor

这些是Laravel中的魔术方法。
这意味着它们将按以下方式处理:

  1. getFullNameAttribute 被剥离了 getattribute;只剩下 FullName.
  2. 这将被转换成 snake_case,结果是 full_name
  3. 然后将此值添加到 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
所有magic getter(和setter)都是这样,他们会根据他们的PascalCase.

转换成snake_case

有趣的是,您可以执行以下操作并且它会起作用:

getfull_nameAttribute()
{
    // ...
}

Relevant framework code.
Laravel 只关心 getAttribute 书挡。