1

我正在使用 Laravel 4,我需要从我的数据库中获取条目,将它们放入一个数组中,然后在我的视图中的 foreach 循环中使用它们。

我没有收到任何错误,但我也没有从数据库中得到任何东西。

我正在尝试编辑 Laravel 捆绑包的此页面以从数据库中获取产品,而不是静态地获取产品。

这是我的模型查询

return $products = \DB::select('select * from products', array('sku', 'name'));

控制器...

public function getIndex()
{
    // Get the products.
    //
    $products = Products::all();

    // Show the page.
    //
    return View::make('shpcart::home')->with('products', $products);
}

这是我的看法

<pre>
<?php
   print_r($products);
?>
</pre>

这是结果

大批 ( )

这适用于插入数据库:

DB::insert('insert into products (sku, name) values (?, ?)', array('WS004', 'Test'));

这个...

$products = DB::table('products')->get();

foreach ($products as $product)
{
echo $product->sku;
}

返回错误

为 foreach() 提供的参数无效

在这里你可以看到它...

http://wilsonswan.co.uk/collection

提前致谢。

4

2 回答 2

0

You should not return $products as such.

You should perhaps do something like:

public function index()
{
$products = Products::where('sku', '=', 'name')->get();

return View::make('view', compact('products'));
}
于 2013-09-30T13:03:35.330 回答
0

尝试这个:

public function getIndex() {
    $db = DB::table('products as p')
               ->where('p.sku', '=', 'WS004');

    $products = $db->get();

    return View::make('shpcart::home')
              ->with('products', $products);
}
于 2013-12-22T13:08:17.547 回答