我将首先解释表格以及代码如何工作
表格
我有:
代码如何运作
当我创建项目时,我也创建了两个项目翻译(每个区域设置一个,例如:' 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');
}
答案 0 :(得分:2)
希望这可以帮到你
public function destroyClient($id) //Destruir cliente y todo lo relacionado de la bbdd
{
$cliente = Client::find($id);
$cliente_project = DB::table('client_project')->where('client_id', $id)->first();
$project_id = $cliente_project->project_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.
DB::table('projects')->where('id',$project_id)->delete();
DB::table('project_translations')->where('project_id',$project_id)->delete();
return redirect()->route('admin.clients');
}
也许更好的方法是使用外出键
答案 1 :(得分:1)
我想你可以试试这个:
public function destroyClient($id) //Destruir cliente y todo lo relacionado de la bbdd
{
$cliente = Client::find($id);
$cliente->delete(); //delete the client
$project = DB::table('client_project')->where('client_id',$id)->first();
DB::table('client_project')->where('client_id',$id)->delete();
DB::table('projects')->where('id',$project->project_id)->delete();
DB::table('project_translations')->where('project_id',$project->project_id)->delete();
return redirect()->route('admin.clients');
}
希望这对你有用!!!
答案 2 :(得分:1)
以下代码将首先获得与客户相关的所有项目。然后将通过循环删除客户端的所有项目。
public function destroyClient($id)
{
$cliente = Client::find($id);
$cliente->delete(); //delete the client
// get list of all projects of client
$projects = DB::table('client_project')->where('client_id',$id)->get();
DB::table('client_project')->where('client_id',$id)->delete();
// delete all projects of client
foreach($projects as $project)
{
DB::table('projects')->where('id',$project->id)->delete();
DB::table('project_translations')->where('project_id',$project->id)->delete();
}
return redirect()->route('admin.clients');
}