dsour68888 2014-11-05 17: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 18: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条)

报告相同问题?

悬赏问题

  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色