[英]Delete rows with Laravel query builder and LEFT JOIN
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. 似乎Laravel不支持使用左连接从多个表中删除。
Is there a supported way or workaround? 是否有受支持的方式或解决方法?
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 文档: 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: 要使laravel允许连接删除很简单 - 您只需要将Illuminate\\Database\\Query\\Grammars\\Grammar
的compileDelete函数更改为:
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. 然后 - > delete()将按照您期望的方式工作。 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. 我已经将这个作为拉取请求添加到laravel框架repo中,所以希望这可能会合并到下一个版本中 - 只需看看。
DB::table(DB::raw('deadline, job'))
might work. DB::table(DB::raw('deadline, job'))
可能有效。 If it doesn't, you'll have to write the SQL manually and call it via DB::statement()
. 如果没有,则必须手动编写SQL并通过DB::statement()
调用它。
$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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.