【发布时间】:2020-03-11 18:54:52
【问题描述】:
我有两张表 Company 和 Employee
在关系中,Company 是父表,Employees 是子表。
现在我需要从父表中删除记录,而父表又必须删除所有相关的子表。
如何做到这一点?
它给了我以下错误
消息:“模型 [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>
【问题讨论】:
-
嗯,如果总是这样,为什么在级联上不删除?
-
或者可能覆盖模型中的删除方法以调用
$this->employees()->delete();和之后的 parent::delete() -
你的意思是这样 $user = Company::findOrFail($id); $用户->删除();员工::where('company_id',$id)->delete(); $this->employees()->delete(); return ['message'=>'公司删除成功'];
-
您的错误消息通常仅在您执行
Employee::findOrFail($id)时出现。你哪里有这样的电话?我在您的代码中没有看到它。你也有堆栈跟踪吗? -
另外一种更简洁的方法是在 laravel 中使用 Observer pattern。这样您就可以从
CompanyController中删除Employee::delete()调用并将其移动到自己的CompanyObserver::deleted()函数中。
标签: jquery mysql laravel vue.js axios