douxi8759 2016-06-12 13:46
浏览 148
已采纳

将模型集合转换为id为key的数组

I am using Laravel HTML component to create a dropdown to list all the groups to which an user can belong.

The list of groups comes from a Groups table.

Currently in my controller my code looks like

    $groups = array();
    $groupModels = Group::all(['id', 'name']);

    foreach ($groupModels as $groupModel) {
        $groups[$groupModel->id] = $groupModel->name;
    }

    return view('myview', compact('groups'));

and in my view I have the following code to create the dropdown

    {!! Form::select('group', $groups, null, ['class' => 'form-control']) !!}

This works, but I am trying to see if there is a way to avoid the foreach loop and directly convert the list of Models into an array. Is it possible?

  • 写回答

1条回答 默认 最新

  • dqg95034 2016-06-12 13:58
    关注

    Use pluck() method:

    $groups = Group::pluck('name', 'id');
    return view('myview', compact('groups'));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: