Delete rows with Laravel query builder and LEFT JOIN

孤街醉人 提交于 2019-12-04 13:10:08

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

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.

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().

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