繁体   English   中英

Laravel自定义样式列表从Eloquent Collection到Form :: select

[英]Laravel custom format lists from Eloquent Collection to Form::select

我有实体城市。 通常我可以使用City::lists("name", "id")以html Form :: select显示。

还需要在城市名称旁边的表格中显示国家/地区代码。 是否有任何Eloquent Collection方法支持建议使用foreach并手动构建阵列?

您可以在此处使用属性访问器 将此添加到您的模型:

public function getNameWithCountryCodeAttribute(){
    return $this->attributes['name'] . ' ' . $this->attributes['country_code'];
}

然后在lists()使用该动态属性。 请注意,您必须首先获取集合,因此您实际上是在集合而不是查询生成器上调用lists()

City::all()->lists('nameWithCountryCode', 'id')

要将查询的列减少到所需的最小值:

City::get(['id', 'name', 'code'])->lists('nameWithCountryCode', 'id')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM