我正在使用 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
的对象(test1
和 test2
)。
我的 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/