【问题标题】:Laravel 4 MySQL query to array?Laravel 4 MySQL查询到数组?
【发布时间】:2013-10-06 08:34:04
【问题描述】:

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

提前致谢。

【问题讨论】:

  • 看起来您没有将 $products 变量传递给视图
  • 抱歉,我没想到要包含控制器。我在上面编辑过。
  • 也许你应该在github上创建一个问题:github.com/rktaiwala/Shpcart/issues
  • 你的产品模型是什么样子的

标签: mysql arrays laravel


【解决方案1】:

您不应该这样退回 $products。

你或许应该这样做:

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

return View::make('view', compact('products'));
}

【讨论】:

【解决方案2】:

试试这个:

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

    $products = $db->get();

    return View::make('shpcart::home')
              ->with('products', $products);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-16
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    相关资源
    最近更新 更多