【发布时间】:2018-09-06 03:59:31
【问题描述】:
我在ingredients 和images 之间有一个数据透视表。在Image 模型上,我有一个自定义删除方法,可以从 s3 存储中删除图像。问题是,如果我在数据透视表外键上使用onDelete('cascade'),delete() 方法将不会被触发。
我尝试了一种解决方法,但没有成功。
我的Ingredient 模特:
class Ingredient extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['ingredient_category_id', 'name', 'units', 'price'];
///////////////////
// Relationships //
///////////////////
public function images() {
return $this->belongsToMany(Image::class, 'ingredient_images')->withTimestamps();
}
/////////////
// Methods //
/////////////
public function delete()
{
$this->images()->delete();
$this->images()->detach();
return parent::delete();
}
}
我的Image 模特:
class Image extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['title', 'path'];
///////////////////
// Relationships //
///////////////////
public function ingredients() {
return $this->belongsToMany(Ingredient::class, 'ingredient_images')->withTimestamps();
}
/////////////
// Methods //
/////////////
public function delete()
{
$this->ingredients()->detach();
Storage::disk('s3')->delete($this->path);
return parent::delete();
}
}
我的pivot 表(ingredient_images):
public function up()
{
Schema::create('ingredient_images', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('ingredient_id');
$table->foreign('ingredient_id')->references('id')->on('ingredients');
$table->unsignedInteger('image_id');
$table->foreign('image_id')->references('id')->on('images');
$table->timestamps();
});
}
我尝试在Ingredient 模型上使用自定义delete() 方法调用images() 删除方法,问题是delete() 来自Image 模型的方法没有被调用(这是假设从存储中删除图像并将其从数据透视表中分离)
当我尝试时:
Ingredient::findOrFail($ids)->images()->delete()
Ingredient::findOrFail($ids)->delete()
我明白了:
完整性约束违规:1451 无法删除或更新父行:外键约束失败
【问题讨论】: