Я использовал отношения многие ко многим. У меня есть три таблицы: product, tag, 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'));
}