Php递归方法获取产品

标签 php laravel recursion laravel-5

此时我正在尝试递归地从指定类别的子项中获取所有产品。

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

这是我目前的方法:

 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

如果有人能帮助我,我将不胜感激。

最佳答案

在 Laravel 中,

hasMany() 和 belongsTo() 创建父子类别关系。

只需在扩展 Eloquent 的模型中使用。示例,

    public function getChildValues() {
        return $this->hasMany('Category', 'parentid');
    }     

    public function getParentValues() {
        return $this->belongsTo('CategoryMN', 'id');
    } 

This link可能对你有帮助。

例如,在 Controller 中检索,

$categories_child = Category::with('getChildValues')->get(); 

关于Php递归方法获取产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31703936/

相关文章:

Laravel 子域路由与资源 Controller

javascript - Laravel5 : Many to many relationship

c++ - 使用递归与迭代在链表末尾插入

c++ - 递归的概念

PHP文件上传而不刷新页面

php - 在 laravel artisan 中从命令行下载文件

php - 未确定的字符串文字错误

java - 如何仅通过这种回溯找到第一个解决方案

php - 登录系统密码和用户名

php - 在字符串中选择从位置到行尾