dsour68888 2014-11-05 09:17
浏览 332
已采纳

Laravel Eloquent将数据提取到自定义数组中

I've tried searching for a way to do this with Laravel, and i'm sure it's more than capable (Maybe i've been searching for it using incorrect terms)..

I'm trying to extract table data to be used in Laravels built-in form creator:

$clusters = Cluster::get(array('id','name'));

Into:

{{ Form::select('cluster', $clusters,Input::old('cluster'), array('id' => 'cluster')) }}

But currently, I get a dropdown with JSON in it, and if I use toArray() it doesn't use the ID numbers from the JSON array, it applies new ID numbers, then puts the data in an array:

Badly formed array using toArray from JSON object

Can anyone point me in the right direction to form arrays properly from Eloquent extractions? I've been using this bit of code which feels meaningless:

$clust = array();
foreach($clusters as $key => $cl) {
  $clust[$cl['id']] = $cl['location'];
}

Thanks

  • 写回答

2条回答 默认 最新

  • doucai5315 2014-11-05 10:52
    关注

    Use lists(), which will return an array of column values, and an optional identifier for them.

    // Controller
    $clusters = Cluster::lists('name', 'id');
    
    // View
    {{ Form::select('cluster', $clusters) }}
    

    lists() is a Query Builder method. All Query Builder methods are available to Eloquent models.


    FYI: When using the Form helpers, it will automatically fill the old input if it exists, so you don't need to specify it. Also, the helper will generate an ID based on the name of the element automatically, so that can be excluded, also.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部