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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog