php - Laravel 4 - 从数据库中检索对象

标签 php mysql laravel

我正在使用 Laravel 并在我的 MySql 数据库中创建了一个类别表,其中包含用于使用树遍历导航的字段:

id | parent_id | name  | lft | rgt | depth 
 1 |      NULL | test1 | 1   | 2   |     0
 2 |      NULL | test2 | 3   | 4   |     0
 3 |         1 | test3 | 5   | 6   |     1

我想检索具有 depth = 0 的对象(test1test2)。

我的 Controller 中有这个功能:

public function getIndex() {
  $categories = array();

  foreach(Category::all() as $category)
  {
      $categories[$category->depth = '0'] = $category->name;
  }

  return View::make('categories.index')
      ->with('categorieslist', $categories);
}

但它总是返回最后一项 (test2)。它需要返回所有 depth = 0 的对象。 有什么想法吗?

最佳答案

问题是您将数据保存(并覆盖)到数组 $categories 的位置 $category->depth = '0'

不熟悉 Laravel,但这应该可以解决问题:

public function getIndex() {
    $categories = array();

    foreach(Category::all() as $category) {
        //If depth equals zero
        if ($category->depth == 0) {
            //append $category->name to $categories
            $categories[] = $category->name;
        }
    }

    return View::make('categories.index')->with('categorieslist', $categories);
}

关于php - Laravel 4 - 从数据库中检索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26998779/

相关文章:

laravel - 为什么Laravel dd只显示两个级别?

php - 分页链接无法正常工作 - 不正确的 PHP 函数?

php - 错误设置证书验证位置 : CAfile ca-bundle. crt CApath:无

c# - Entity Framework 在 where 子句上添加了一个额外的条件

非事件用户时的 PHP 邮件

没有重复值的MySQL连接查询

php - 如何合并从mysql查询得到的多个数组,然后遍历新数组

php - 使用 Symfony 在 2 个表之间建立多个连接表

php - 如何保存/重定向 Laravel Artisan 命令的输出?

php - 碳: diffForHumans() displaying wrong statement