首页 > 解决方案 > 当我添加产品,选择类别时,它是否应该只选择与该类别相关的子类别?

问题描述

当我添加产品,选择类别时,它是否应该只选择与该类别相关的子类别?

我希望当我在/产品/创建并选择一个类别时,在下面显示与所选类别相关的子类别。我只是不知道该怎么做。

产品控制器创建

public function create()
{
  $categories = Category::all();
  $subcategories = Subcategory::all();

  return view('products.create', compact('categories', 'subcategories'));
}

创建产品刀片

<div class="form-group">
 <label for="category_id">Categorie :</label>
  <select class="custom-select w-50 d-block" id="category_id" name="category_id">
   @foreach($categories as $categorie)
    <option value="{{ $categorie->id }}">{{ $categorie->name }}</option>
   @endforeach
  </select>
</div>
<div class="form-group">
 <label for="subcategory_id">Subcategorie :</label>
  <select class="custom-select w-50 d-block" id="subcategory_id" name="subcategory_id">
   @foreach($subcategories as $subcategorie)
    <option value="{{ $subcategorie->id }}">{{ $subcategorie->name }}</option>
   @endforeach
  </select>
</div>

子类别模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Subcategory extends Model
{
    protected $fillable = ['name', 'category_id',];

    public function category()
    {
        return $this->belongsTo('App\Category', 'category_id');
    }

    public function products()
    {
        return $this->hasMany('App\Product','category_id');
    }

}

类别模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['name', 'image',];

    public function products()
    {
        return $this->hasMany('App\Product','category_id');
    }

    public function subcategories()
    {
        return $this->hasMany('App\Subcategory', 'category_id');
    } 

}

数据库:

Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('category_id');
            $table->string('subcategory_id');
            $table->string('image');
            $table->string('description');
            $table->string('tag');
            $table->timestamps();
        });
Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('image');
            $table->timestamps();
        });
Schema::create('subcategories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('category_id');
            $table->string('image');
            $table->timestamps();
        });

标签: relational-databaserelationshiplaravel-6

解决方案


推荐阅读