Delete rows with Laravel query builder and LEFT JOIN

六眼飞鱼酱① 提交于 2019-12-21 20:54:16

问题


How to delete rows from multiple tables in one query (with left join). The query:

DELETE `deadline`, `job` FROM `deadline` LEFT JOIN `job` ....

So, I try it like this:

DB::table('deadline', 'job')
    ->leftJoin('job', 'deadline.id', '=', 'job.deadline_id')
    ->where('deadline.id', $id)
    ->delete();

Seems that Laravel doesn't support delete from multiple tables with left join.

Is there a supported way or workaround?


回答1:


It seems that my way is not possible. So, I did it like this.

$q = 'DELETE deadline, job FROM deadline LEFT JOIN job ...where deadline.id = ?';        
$status = \DB::delete($q, array($id));

Documentation: http://laravel.com/docs/database#running-queries




回答2:


To make laravel allow a join in a delete is simple - you just need to change the compileDelete function in Illuminate\Database\Query\Grammars\Grammar to this:

public function compileDelete(Builder $query)
{
    $table = $this->wrapTable($query->from);

    $components = implode(' ', array(
        is_array($query->joins) ? $this->compileJoins($query, $query->joins) : '',
        is_array($query->wheres) ? $this->compileWheres($query, $query->wheres) : '',
        is_array($query->limit) ? $this->compilelimit($query, $query->limit) : '',
        is_array($query->offset) ? $this->compileOffset($query, $query->offset) : ''
    ));

    return trim("delete $table from $table ".$components);
}

Then ->delete() will work the way you expect it to. I've already added this as a pull request to the laravel framework repo, so hopefully this might be merged into the next version - just have to see.




回答3:


DB::table(DB::raw('deadline, job')) might work. If it doesn't, you'll have to write the SQL manually and call it via DB::statement().




回答4:


$query = 'DELETE courses,course_contents FROM courses 
          INNER JOIN course_contents ON course_contents.course_id = courses.id  
          WHERE courses.id = ?';

\DB::delete($query, array($id));


来源:https://stackoverflow.com/questions/23802662/delete-rows-with-laravel-query-builder-and-left-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!