【发布时间】:2019-03-23 02:40:13
【问题描述】:
我使用了多对多关系。我有三个名为:product、tag、productstag 的表。在这里,我希望每当我要删除一个产品时,它也会删除它在 productstag 表上的关系。
public function up()
{
Schema::create('productstags', function (Blueprint $table) {
$table->integer('product_id');
$table->integer('tag_id');
$table->primary(['product_id','tag_id']);
$table->timestamps();
});
}
如您所见,我使用 product_id 和 tag_id 作为主键。 所以我不能用这个
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('products')->onDelete('cascade');
那还有什么办法呢?
在我的产品模型上
public function tags()
{
return $this->belongsToMany('App\Tag','productstags','product_id','tag_id')->withTimestamps();
}
在我的标签模型上:
public function products()
{
return $this->belongsToMany('App\Product','Productstags','tag_id','product_id');
}
关于我的产品销毁功能:
public function destroy(Request $request,$id)
{
$product=Product::findOrFail($id);
if($request->file('image')==''){
$input=$request->except('photo_id');
}
else{
$input=$request->all();
unlink(public_path()."/images/".$product->image->name);
}
$product->delete($input);
Session::flash('deleted_user','the user has been deleted');
return redirect(route('product.index'));
}
【问题讨论】:
-
product_id和tag_id是primary key是否有特定原因? -
是的! @AlbertoGuilherme
标签: laravel many-to-many