dongrao9436
dongrao9436
2017-11-21 05:02
浏览 275
已采纳

如何在laravel中选择特定列时返回附加字段

I added a full_name field to User model like this:

protected $appends = ['full_name'];

public function getFullNameAttribute()
{
    return $this->name . ' ' . $this->family;
}

On the other hand I want to select and return specific columns along with full_name field like this:

return  User::all('user_id', 'username', 'full_name')

But laravel gets this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'full_name' in 'field list' (SQL: select user_id, username, name, family, full_name from users where users.deleted_at is null)

How can I do what I want?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doucigua0449
    doucigua0449 2017-11-21 05:04
    已采纳

    I think you don't need to specify that in your select column.. it's already attached with your result set.

    If you want specific columns, than you need to probably user $hidden attributes and make them visible whenever you want.

    点赞 评论
  • doutangguali32556
    doutangguali32556 2017-11-21 05:06

    You can't use append attribute in query.

    the full_name only can be access after query.. bcoz full_name is not attach with the result

    $users = User::all();
    return $users[0]->full_name; //this requred getFullNameAttribute like above
    

    If you still want to do with query. Do in DB query instead.. this no need to $append attribute. full_name already attach with the result

    return User::select('user_id', 'username' , DB::raw('CONCAT(name, " ", family) AS full_name'))->get();
    
    点赞 评论
  • doumenshi1475
    doumenshi1475 2017-11-21 08:21

    Hello you can get two or more column value concated using query like this,

     return  $user = User::select('user_id', 'username',DB::raw("CONCAT('first_name', " ",'last_name') AS full_name" 'full_name');
    

    Or if you want to concat column from retrieved array you can do like this,

    $user = User::all();
    foreach($user as $single){
       $user->full_name = $single->first_name ." ".$single->last_name
    }
    print_r($user);
    

    happy coding.

    点赞 评论

相关推荐