我需要执行一个删除操作,其中包括一个子查询。它是这样的:
delete from images where exists ( select thumbnail from posts where posts.id = 10 )
我如何使用where Exists函数来实现这一点?我试图通过一个变量动态地传递整数值,但它抛出了一个错误,说变量没有定义。未在闭包内部检测到变量。我怎么能那样做?
注意:查询中的10是php传入的值。
您需要这样做:
$postId = Input::get('postId');
DB::table('posts')
->whereExists(function($query) use ($postId) {
// now you have $query and $postId
$query->select('thumbnail')
->from('posts')
->where('id', '=', $postId);
})->delete();
PS:在同一张表中使用EXISTS
似乎很奇怪。你不能简化成这样吗(?):
delete from posts where posts.thumbnail is not null and posts.id = 10