首页 > 解决方案 > Laravel 雄辩的分类

问题描述

我有一个关于 laravel 雄辩的问题。

数据库表

类别: id root_id 名称

产品ID名称等。

product_categories id product_id category_id

因此,可能是 CategoryA 有一个子 CategoryB,而 CategoryB 本身有一个子 CategoryC。

当我单击 CategoryA 时,我想查找属于 CategoryA、CategoryB、CategoryC 的所有产品

Category Model

   public function cats()
    {
        return $this->hasMany(Category::class);
    }


    public function childrenCategories()
    {
        return $this->hasMany(Category::class)->with('cats');
    }

产品型号

public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

控制器

//首先我得到所有类别的所有ID,所有级别的子类别。

        $categories = Category::where('category_id',$category_id)->with('childrenCategories')->get();
        $all_cat_array=array();$all_prod=array();

foreach ($categories as $category)
{
    foreach ($category->childrenCategories as $childCategory) {
        array_push($all_cat_array, $childCategory->id);
    }
    array_push($all_cat_array,$category->id);

}

//然后我得到所有产品的ID

foreach ($all_cat_array as $cat)
{
    if(CategoryProduct::where('category_id',$cat)->exists()) {
        $prod=CategoryProduct::where('category_id',$cat)->pluck('product_id');
        array_push($all_prod,$prod );
    }
}

但我不想使用所有这些 foreach,因为我想优化代码。我该怎么做才能使它更简单???

标签: laraveleloquent

解决方案


更多信息请阅读Laravel 文档

数据库

A类数据库

Schema::create('category_as', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->unsignedBigInteger('product_id');
  ...
  $table->timestamps();

  $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});

B类数据库

Schema::create('category_bs', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->unsignedBigInteger('category_a_id');
  ...
  $table->timestamps();

  $table->foreign('category_a_id')->references('id')->on('category_as')->onDelete('cascade');
});

模型

产品型号

public function categories_a() {
  return $this->hasmany(Category_a::class);
}

A类型号

public function categories_b() {
  return $this->hasmany(Category_b::class);
}

public function product() {
  return $this->belongsTo(Product::class);
}

B类型号

public function category_a() {
  return $this->belongsTo(Category_a::class);
}

public function clients() {
   return $this->hasManyThrough(Client::class, Code::class);
}

控制器

public function index() {
  $products = Product::all();
  $query = $products->categories_a->categories_b;
  dd($query);
}

已编辑

数据库

A类数据库

Schema::create('categories', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->unsignedBigInteger('product_id');
  ...
  $table->timestamps();

  $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});

模型

产品型号

public function categories() {
  return $this->hasmany(Category::class);
}

类别型号

public function product() {
  return $this->belongsTo(Product::class);
}

控制器

public function index() {
  $products = Product::all();
  $query = $products->categories;
  dd($query);
}

推荐阅读