【发布时间】:2015-07-30 23:46:06
【问题描述】:
此时我正在尝试以递归方式从指定类别的子项中获取所有产品。
我正在使用 laravel 并在 App/Helpers 中创建了一个类来处理这个问题,因此它将被自动加载。
数据库的结构如下 分类:
1|0|2015-07-28 14:45:38|2015-07-28 14:45:38
2|1|2015-07-28 14:52:43|2015-07-28 14:56:47
产品:
1|2|2015-07-28 15:10:45|2015-07-29 11:04:44
因此产品的类别 id 为 2。类别 2 的父 id 为 1。因此,如果用户在类别 1 的页面上,他/她需要查看属于类别 1 和类别 2 的产品,因为 2 是第 1 类的孩子。
这是我目前的方法:
public static function getProducts($id) {
self::$products = DB::table('products')->where('category_id', $id )->get();
$categories = DB::table('categories')->where('parent_id', $id)->get();
if ($categories !== null) {
foreach ($categories as $category) {
array_merge(self::$products, self::getProducts($category->id) );
}
}
return self::$products;
}
希望有人能帮我递归检索所有属于子类别的产品。
更新:
我安装了 Laravel 调试工具栏,发现我的查询在加载网页时没有返回任何结果。当我用我的 sql 客户端查询它时,我确实得到了正确的结果。
这是我目前从子类别中获取所有产品的方法:
public static function getProducts($id)
{
$products = [];
$categories = DB::table('categories')->where('parent_id', $id)->get();
array_merge($products, DB::table('products')->where('category_id', $id)->get());
if ($categories !== null) {
foreach ($categories as $category) {
self::getProducts($category->id);
}
return $products;
}
}
数据库架构:
CREATE TABLE "products" ("id" integer not null primary key autoincrement, "url" text not null, "title" text not null, "keywords" text not null, "description" text not null, "content" text not null, "attributes" text not null, "pdf" text not null, "image" text not null, "category_id" integer not null, "created_at" datetime not null, "updated_at" datetime not null);
CREATE TABLE "categories" ("id" integer not null primary key autoincrement, "url" text not null, "title" text not null, "keywords" text not null, "description" text not null, "content" text not null, "parent_id" integer not null, "created_at" datetime not null, "updated_at" datetime not null);
还打开了调试栏和站点=>http://remotefix.nl:81/producten/flenzen
如果有人可以帮助我,我们将不胜感激。
【问题讨论】:
标签: php laravel recursion laravel-5