【发布时间】:2018-12-06 07:07:12
【问题描述】:
我尝试了很多时间但失败了。 例如:我想要的结果就像我将产品插入数据库并选择多个类别并将它们存储在不同的表中然后向我显示这样的错误:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'space.category_product' doesn't exist (SQL: insert into `category_product` (`category_id`, `product_id`) values (1, ))
如果我手动将数据库表从 category_products 重命名为 category_product,则会在下面显示一个新错误:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'product_id' cannot be null (SQL: insert into `category_product` (`category_id`, `product_id`) values (1, ))
这是我的数据库代码
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('model');
$table->string('slug')->unique();
$table->string('availability');
$table->float('price');
$table->longText('images');
$table->text('short_detail');
$table->text('feature');
$table->longText('purchase_delivery');
$table->longText('replace_policy');
$table->timestamps();
});
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug');
$table->timestamps();
});
Schema::create('category_products', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned();
$table->foreign('product_id')->references('id')->on('products')->onUpdate('cascade')->onDelete('cascade');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
这是我的模型:
class Category extends Model
{
public function Products()
{
return $this->belongsToMany(Product::class);
}
}
class Product extends Model
{
public function Categories()
{
return $this->belongsToMany(Category::class);
}
}
产品控制器:
public function store(Request $request)
{
if ($request->hasFile('file')){
foreach ($request->file as $file) {
$fileExt = $file->getClientOriginalExtension();
$uniqId = uniqid('img-');
$fileName[] =$uniqId.'.'.$fileExt;
$Name = $uniqId.'.'.$fileExt;
$file->move('public/uploads',$Name);
}
$images = implode(",",$fileName);
$product = new Product();
$product->Categories()->attach($request->categories_id);
$product->name= $request->input('name');
$product->model= $request->input('model');
$product->slug= $request->input('slug');
$product->availability= $request->input('availability');
$product->price= $request->input('price');
$product->images= $images;
$product->short_detail= $request->input('short_detail');
$product->feature= $request->input('feature');
$product->purchase_delivery= $request->input('purchase_delivery');
$product->replace_policy= $request->input('replace_policy');
if ($product->save()) {
return redirect()->route('product.index')
->with('success', 'Product Added successfully');
}
return back()->withInput()->with('errors', 'Error Adding New Product');
}
}
【问题讨论】:
标签: php laravel database-design eloquent