gpt4 book ai didi

php - 在 Laravel 4 中使用数据库结果填充下拉菜单

转载 作者:可可西里 更新时间:2023-11-01 06:31:55 26 4
gpt4 key购买 nike

我正在尝试在 Laravel 4 中使用数据库结果填充下拉菜单。我对 Laravel 非常陌生。这实际上是我的第一个网站,我边走边学。因此,如果我使用了错误的术语或信息不足,请告诉我。

我有一个公司信息数据库,我需要用户能够从下拉列表中选择一家公司。或者,如果公司不在数据库中,则添加它。

对于选择菜单,它需要像这样:

[公司名称结果]

我在我的 Controller 中使用这段代码:

$companies = RecordCompany::get();
$company_selector = array();

foreach($companies as $company) {
$company_selector[$company->id] = $company->id;
$company_selector[$company->company_name] = $company->company_name;
}

return View::make('admin.record_new', array('company_selector' => $company_selector));

这就是我的观点:

@if(count($client_selector)>0)
{{ Form::select('company_id', $company_selector, array_values($company_selector)[0]) }}
@endif

免责声明:我在网上找到了这段代码。

首先,我不明白它如何在我不告诉它把数据放在哪里的情况下填充值和选项文本。

其次,返回的错误是意外的。当我取出表单代码中的 [0] 时,它告诉我 $company_selectorundefined

我在这里做错了什么?

最佳答案

为了使用 RecordCompany 模型中的所有记录填充下拉菜单,您可以在您的 View 中执行以下操作:

{{ Form::select('company_id', RecordCompany::lists('company_name', 'id')) }}

Note: In Laravel 5, the method lists has been deprecated. Use pluck instead.

代码解释:

  1. Form::select 方法创建一个 HTML 选择标签。
  2. company_id 是选择标签的名称。
  3. 第二个参数是选择标签的选项。任何模型(本例中为 RecordCompany)中的 lists 方法都会生成一个关联数组,其中包含传递给该方法的参数(本例中的 idcompany_name case) 模型的数据库表中的所有记录。

如果需要,您还可以从 Controller 调用lists 方法,然后将值传递给 View ,如下所示:

在 Controller 中

$company_lists = RecordCompany::lists('company_name', 'id');

return View::make('admin.record_new', array('company_lists' => $company_lists));

在 View 中

{{ Form::select('company_id', $company_lists) }}

您可以在此处查看用于生成下拉列表的 Laravel 4 文档:http://laravel.com/docs/html#drop-down-lists

关于php - 在 Laravel 4 中使用数据库结果填充下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21937116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com