【问题标题】:Populating dropdown using Laravel Eloquent and DB使用 Laravel Eloquent 和 DB 填充下拉列表
【发布时间】:2014-08-18 00:24:05
【问题描述】:

我正在使用 Laravel 和 Eloquent,并尝试使用选择查询的结果填充视图的下拉框。

在我的控制器中:

public function uploadDocs($userid)
{
    $doc_options = DB::select('select document.document_description from document where user_id = ?', array($userid));

    return View::make('uploaddocs')->with('doc_options', $doc_options);
}

在我看来:

<body>
{{ Form::select('doc_options_id', $doc_options) }}
</body>

我得到以下堆栈跟踪:

htmlentities() expects parameter 1 to be string, object given (View: /home/vagrant/code/eduview/app/views/uploaddocs.blade.php)

有什么想法吗?谢谢。

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    试试

    $doc_options = DB::statement(DB::raw('select document.document_description from document where user_id = ?', array($userid)))-&gt;get();

    编辑:我可能应该先解释一下。

    DB::select() 主要用于数据库构建器,以便链接到其他可链接的函数,而不是用于执行整个查询。

    您可以使用DB::statement 在其中提供新的自定义 SQL 查询,但您还必须指定 statement() 参数的内容将是原始查询。因此DB::raw

    您也可以利用 Eloquent 或 Laravel 的查询构建器,在 app/models 中创建一个名为 Document 的 Eloquent 模型,其内容如下:

    class Document extends Eloquent {}

    并将上面的查询替换为:

    $doc_options = Document::select('document_description')-&gt;where('user_id','=',$userid)-&gt;get()

    【讨论】:

      【解决方案2】:

      您正在将一个对象传递给 Form::select() 助手,它需要一个数组。

      相反,Laravel 有内置的工具可以做到这一点。请参阅 Laravel 文档中 Selects 下的 lists() 方法:

      public function uploadDocs($userid)
      {
          $doc_options = DB::table('document')->where('user_id', $userid)->lists('document_description');
      
          return View::make('uploaddocs')->with('doc_options', $doc_options);
      }
      

      应该是这样的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-18
        • 2012-11-07
        • 2016-05-12
        • 2011-08-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多