我有一个由select2.js 提供服务的表单
在我的控制器中,我生成了一个带有选择内容的var:
$gau = array(null => 'Gautor...') + Gauthor::orderBy('surname','asc')->lists('surname', 'id')->all();
在我看来,我这样做:
{!! Form::select('gauthor_id', $gau, Session::get('aut'), array('id'=>'gauthor_id')) !!}
在我的表中,我有两列:surname
和firstnames
。
在我的Gauthor
模型中,我这样合并它们:
public function getFullnameAttribute()
{
return $this->firstnames . ' ' . $this->surname;
}
以便在我的视图文件中以这种方式显示值CCD_ 4。
我尝试做的事情:我想在我的选择框中看到全名。如何做到这一点,而不在我的数据库中创建另一个全名列?
我尝试过的:我试着用控制器中的fullname
替换surname
,但这太容易了。我得到SQL错误:列"全名"找不到
感谢
试试这个代码,没有测试
Gauthor::selectRaw('id, CONCAT(firstnames, " ", surname) as fullname')
->orderBy('fullname','asc')->lists('fullname', 'id');
selectRaw('id, CONCAT(firstnames, " ", surname) as fullname')
将选择id
和fullname
(由名字和姓氏连接)。然后你可以用->lists('fullname', 'id')
列出这两个。
额外的->get()
发挥了神奇的作用。整行应该是这样的:
$gau = array(null => 'Gautor...') + Gauthor::orderBy('surname','asc')->get()->lists('fullname', 'id')->all();
如果要包含模型的id
,则需要在select2
调用中包含以下选项:
$(document).ready(function() {
$("select").select2({
templateResult: function(state) {
if (!state.id) { return state.text; }
return state.id + ' - ' + state.text;
}
});
});
而不是这个:
$("select").select2();