使用Laravel Eloquent和DB填充下拉列表

时间:2014-08-18 00:24:06

标签: php mysql laravel eloquent

我正在使用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)

有什么想法吗?感谢。

2 个答案:

答案 0 :(得分:0)

尝试

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

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

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

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

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

class Document extends Eloquent {}

并将上面的查询换成:

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

答案 1 :(得分:0)

您正在将一个对象传递给Form::select()帮助器,并且它正在期待一个数组。

相反,Laravel拥有内置的工具来做到这一点。请参阅Selects下的Laravel文档中的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);
}

应该是它。