relational-database - 当我添加产品,选择类别时,它是否应该只选择与该类别相关的子类别?
问题描述
当我添加产品,选择类别时,它是否应该只选择与该类别相关的子类别?
我希望当我在/产品/创建并选择一个类别时,在下面显示与所选类别相关的子类别。我只是不知道该怎么做。
产品控制器创建
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();
});
解决方案
推荐阅读
- c# - 获取字符串的一部分 - C# .NET Core 3.1
- firebase-storage - 由于我没有上传任何内容,Firebase 存储桶逐渐填满
- drag-and-drop - Blazor - ondrop 事件不返回文件对象
- css - PowerApps:在 HTML 文本控件中缩放图像
- android - androidx - 在 Activity 中实现 androidx 首选项 (Kotlin)
- reactjs - 条形图:如何在每个条形图的顶部显示 y 值(react-native-pure-chart)
- javascript - 我可以使用 javascript 在跨度文本上附加锚标记吗
- javascript - 如何使用事件 DRY 创建函数?
- ios - 使用自动填充支持更改密码
- python - 当页面偏移值永远不会结束时如何进行网页抓取