gpt4 book ai didi

jquery - 根据 Laravel Vue Js Api 中的关系从多个表中删除数据

转载 作者:行者123 更新时间:2023-11-29 09:30:16 26 4
gpt4 key购买 nike

我有两个表“公司”和“员工”

在关系中,公司是父表,员工是子表。

现在我需要从父表中删除记录,而父表又必须删除所有相关的子表。

如何做到这一点?

它给了我以下错误

message: "No query results for model [App\Employee] 2"

模态代码是:

public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('BadgeCode')->unique();
$table->integer('company_id');
$table->timestamps();
});
}

API代码是:

Route::apiResources(['company'=>'API\CompanyController']);

CompanyController 中的代码是:

 public function destroy($id)
{
$this->authorize('isAdmin');
$user = Company::findOrFail($id);
Employee::where('company_id',$id)->delete();
$user->delete();
return ['message'=>'Company Deleted Successfully'];
}

我的 Company.Vue 脚本代码:

deletecompany(id) {
if (this.$gate.isAdmin()) {
swal
.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!"
})
.then(result => {
//Send request to the server

if (result.value) {
this.form
.delete("api/company"/" + id)
.then(() => {
// swal.fire("Deleted!", "Your file has been deleted.", "success");
toast.fire({
type: "success",
title: "Your Selected Company is successfully deleted!"
});
Fire.$emit("refreshPage");
})
.catch(e => {
console.log(e);
});
}
});
} else {
toast.fire({
type: "error",
title: "You don't permission to perform this action!"
});
Fire.$emit("refreshPage");
}
}

HTML 代码:

<a href="#" v-if="$gate.isAdmin()" @click="deletecompany(company.id)">
<i class="fa fa-trash red"></i>
</a>

最佳答案

您应该在迁移中添加对 company_idonDelete(cascade) 的引用 请参阅此链接 What does onDelete('cascade') mean? ,当您删除一个公司时,会自动删除与该公司关联的所有员工。

public function up() {
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('BadgeCode')->unique();
$table->bigInteger('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
$table->timestamps();
});
}

关于jquery - 根据 Laravel Vue Js Api 中的关系从多个表中删除数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58880095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com