【发布时间】:2017-12-08 15:19:35
【问题描述】:
在我的数据库中,我有 product_category 和 products 一个 product 可能属于 product_category 表中的一个或某个类别,现在我的问题是:当用户提交具有一个或某个类别的产品时,如何我将其保存在数据库中,例如一个类别有一种或某种产品?
在视图中我有多个选择:
{{ Form::select('categories[]', $productCategories, null, array('class' => 'multiselect-success multiselect_selected','multiple'=>'multiple')) }}
products模特:
class Products extends Model
{
protected $table = 'products';
protected $guarded = ['id'];
protected $casts = [
'images' => 'array'
];
public function productCategories()
{
return $this->belongsTo(ProductCategories::class);
}
}
productCategories模特:
class ProductCategories extends Model
{
protected $table = 'product_categories';
protected $guarded =['id'];
protected $casts=[
'images'=>'array'
];
public function products()
{
return $this->hasMany(Products::class);
}
}
和store 函数转换成controller:
public function store(RequestProducts $request)
{
try {
$data = Products::create([
'name' => $request->name,
'amount' => $request->amount,
'product_code' => $request->product_code,
'weight' => $request->weight
/* MY PROBLEM IS HERE */
'category_id' => $request->categories
]);
} catch (Exception $ex) {
...
}
return redirect(route('manageProductCategories.index'));
}
在 html 视图中 categories 是一个数组,我该如何实现它?
更新
使用createMany 更新代码后,我收到此错误:
General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into `products` (`name`, `lang`, `amount`, `product_code`, `weight`, `images`, `updated_at`, `created_at`) values (eqweqwe, fa, 45,000, asd, asdasd, '', 2017-12-09 04:45:44, 2017-12-09 04:45:44))
迁移文件:
public function up()
{
Schema::create('product_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category_name');
$table->string('lang', 2);
$table->text('images');
$table->timestamps();
});
}
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('amount');
$table->string('product_code');
$table->string('weight');
$table->string('lang', 2);
$table->text('images');
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('product_categories')->onDelete('cascade');
$table->timestamps();
});
}
【问题讨论】:
-
在我看来,您需要在产品和具有中间表的类别之间建立多对多关系。
-
@ab_in 我对多对多没有任何问题,但我认为实现是一对多
-
那么您成功创建了产品,现在您需要创建类别并将其附加到您的新产品中吗?
-
是的。将一篇帖子附加到一个或某些类别
标签: php laravel laravel-5 eloquent