[英]How to delete rows from a pivot table in Laravel?
I have a films
table which contains a many to many relation eg AgeRatings
with a pivot table called film_age_rating
which contains a film_id
as a foreign key I have this with 3 other relations too.我有一个包含多对多关系的
films
表,例如AgeRatings
与一个名为film_age_rating
的数据透视表,其中包含一个film_id
作为外键,我也有这个与其他 3 个关系。
Right now my app has no functionality to make a deletion request to remove a film, so right now I hard delete rows in the films
DB table.现在我的应用程序没有功能来发出删除电影的删除请求,所以现在我很难删除
films
数据库表中的行。 When I delete a film from the films
table it deletes items, but the data within the pivot table remains unchanged which I don't want to happen.当我从
films
表中删除films
它会删除项目,但数据透视表中的数据保持不变,这是我不希望发生的。
films_table电影表
public function up()
{
Schema::create('films', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name')->nullable();
}
film_age_rating电影年龄分级
public function up()
{
Schema::create('film_age_ratings', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('age_rating_id');
$table->uuid('film_id');
$table->timestamps();
});
}
Film Model电影模型
public function ageRatings(): BelongsToMany
{
return $this->belongsToMany(
AgeRatings::class,
'film_age_rating',
'film_id',
'age_rating_id'
);
}
Age Rating Model年龄分级模型
public function film(): BelongsToMany
{
return $this->belongsToMany(
Film::class,
'film_age_rating',
'age_rating_id',
'film_id'
);
}
I know an option is to add an onDelete
cascade to the pivot tables, but that will require lots of migration tables.我知道一个选项是将
onDelete
级联添加到数据透视表,但这将需要大量迁移表。 Is there another way to tackle this without adding a DELETE
request for now or is adding the cascade the only option?有没有另一种方法来解决这个问题,而现在不添加
DELETE
请求,或者添加级联是唯一的选择?
Could you please advise me on the most efficient option?你能告诉我最有效的选择吗?
The only way I can imagine is to use softDeletes我能想象的唯一方法是使用softDeletes
On this way, there will be only one query to delete a film, and it will be a logical delete.这样一来,删除一部电影只会有一个查询,而且是逻辑删除。
You can delete data using the sync() method.您可以使用sync()方法删除数据。 It releases the relation from the pivot table.
它从数据透视表中释放关系。 I assuming that you want to delete a film .
我假设您要删除一部电影。 So this is a sample method in your controller.
所以这是您的控制器中的一个示例方法。
public function deleteFilm($id)
{
$film = Film::find($id);
$film->ageRatings()->sync([]);
$film->delete();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.