【发布时间】:2018-01-15 22:42:34
【问题描述】:
我将首先解释表格和代码的工作原理
表格
我有:
- 具有以下字段的项目:id、slug、order、public、pathheader 和 pathhome。
- project_translations 包含以下字段:id、locale、project_id、title 和 caption。
- 具有以下字段的客户端:id、名称、slug 和优先级。
- client_project 包含字段:id、client_id 和 project_id
代码的工作原理
当我创建一个项目时,我也会创建两个项目翻译(每个语言环境一个,例如:'es'、'en')。然后我选择一个客户,这将建立关系 client_project。
当我删除项目时,我同时删除了具有相同project_id的project_translations和project_id相同的client_project行。
我想要什么
当我删除客户端时,删除字段client_id具有相同值的行(这是有效的),然后删除与我删除的客户端有关系的项目的项目和projects_translations。
我的函数目前的样子
public function destroyClient($id) //Destruir cliente y todo lo relacionado de la bbdd
{
$cliente = Client::find($id);
$cliente->delete(); //delete the client
DB::table('client_project')->where('client_id',$id)->delete(); //delete the client_project relations which field client_id is the same that the client i just deleted.
return redirect()->route('admin.clients');
}
【问题讨论】:
-
那么,问题是客户端被成功删除但
client_project和project_transalation中的记录没有被删除? -
你试过
$cliente->projects()->delete();吗? -
暂时用这段代码我只是删除了客户和客户项目的关系。我需要删除项目和 project_translation @SagarGautam
-
你需要优化数据库。建立正确的关系和级联将更容易删除多个表上的记录
-
是的@MisaGH 并且不工作。