Laravel用钥匙获取/地图

时间:2014-04-27 22:53:13

标签: php laravel

我希望我能在一条线上做到这一点:

$users = [];
$rawUsers = User::select('id','first_name','last_name')->where('company_id',Auth::user()->company_id)->get();
foreach($rawUsers as $u) {
    $users[$u['id']] = $u['first_name'].' '.$u['last_name'];
}

我看到Collection类有一个->map函数可以让我进行连接,但我不知道如何通过id索引结果。有办法做我想做的事吗?

1 个答案:

答案 0 :(得分:4)

您可以使用lists方法对查询执行此操作:

User::select(DB::raw('concat(first_name," ",last_name) as full_name'), 'id')->lists('full_name', 'id');
// returns array(id => full_name, ...)

或者在模型上使用accessor,在集合上使用lists

// User model
public function getFullNameAttribute()
{
    return $this->attributes['first_name'].' '.$this->attributes['last_name'];
}

// then on the collection call lists:
$usersRaw = User::where(...)->get()->lists('fullName','id');