我有实体城市。通常我可以使用City::lists("name", "id")
以html形式显示::select。
还需要在城市名称旁边的表格中显示国家代码。Eloquent Collection的任何方法都支持吗?建议使用foreach并手动构建数组?
您可以在此处使用属性访问器。将此添加到您的模型中:
public function getNameWithCountryCodeAttribute(){
return $this->attributes['name'] . ' ' . $this->attributes['country_code'];
}
然后在CCD_ 2中使用该动态属性。请注意,您必须首先获取集合,因此实际上您对集合而不是查询生成器调用lists()
。
City::all()->lists('nameWithCountryCode', 'id')
将查询的列减少到所需的最小值:
City::get(['id', 'name', 'code'])->lists('nameWithCountryCode', 'id')