2014-02-16 70 views
4
echo Form::select(
    'campaign_user_id', 
    User::find(1)->profile->lists('first_name', 'id'), 
    Input::get('campaign_user_id', $campaign->user_id), 
    array(
     "placeholder" => "US", 
     'class' => 'form-control', 
     'disabled' => 'disabled' 
    ) 
) 

上面的代碼用於構建下拉選擇列表。它從數據庫中提取用戶列表。在第3行,你可以看到User::find(1)->profile->lists('first_name', 'id')Laravel 4用2個數據庫列填充下拉列表?

它正在獲取first_name列,我需要以某種方式獲取名字和列名,儘管並將它們組合在列表中。因此該列表值仍然是用戶標識並顯示全名。

任何想法如何使這個工作2 DB列first_namelast_name?或另一種方法來達到我的最終目標?

回答

6

//在你的模型

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

然後抓住像這樣:

User::find(1)->profile->lists('full_name', 'id'); 

OR

User::find(1)->profile->select(DB::raw('concat (first_name," ",last_name) as full_name,id'))->lists('full_name', 'id'); 

我喜歡第一個:)

+0

剛一說明,第一種方法給了我這個錯誤...'列號t發現:1054'字段列表'中的未知列'full_name'(SQL:從'profiles'選擇'full_name','id')'第二個工作雖然,謝謝。我也嘗試將'getFullNameAttribute()'方法添加到我的'User'和'Profile'模型中,但仍然出現該錯誤。 – JasonDavis