在 Laravel 查询构建器中运行“存在”查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26953864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:25:44  来源:igfitidea点击:

Running "exists" queries in Laravel query builder

laravellaravel-4query-builder

提问by Anthony Vipond

I'm using MySQL and have a table of 9 million rows and would like to quickly check if a record (id) exists or not.

我正在使用 MySQL 并且有一个包含 900 万行的表,并且想快速检查记录 (id) 是否存在。

Based on some research it seems the fastest way is the following sql:

根据一些研究,似乎最快的方法是以下 sql:

SELECT EXISTS(SELECT 1 FROM table1 WHERE id = 100)

SELECT EXISTS(SELECT 1 FROM table1 WHERE id = 100)

Source: Best way to test if a row exists in a MySQL table

来源:测试 MySQL 表中是否存在行的最佳方法

How can I write this using Laravel's query builder?

我如何使用 Laravel 的查询构建器来编写这个?

回答by Jarek Tkaczyk

Use selectOnemethod of the Connectionclass:

类的使用selectOne方法Connection

$resultObj = DB::selectOne('select exists(select 1 from your_table where id=some_id) as `exists`');

$resultObj->exists; //  0 / 1;

回答by Mochamad Gufron Efendi

see here http://laravel.com/docs/4.2/queries

见这里http://laravel.com/docs/4.2/queries

Scroll down to Exists Statements, you will get what you need

向下滚动到 Exists Statements,你会得到你需要的

DB::table('users')
->whereExists(function($query)
{
    $query->select(DB::raw(1))
          ->from('table1')
          ->whereRaw("id = '100'");
})
->get();

回答by AbstractVoid

This is an old question that was already answered, but I'll post my opinion - maybe it'll help someone down the road.

这是一个已经回答的老问题,但我会发表我的意见 - 也许它会帮助某人。

As mysql documentationsuggests, EXISTS will still execute provided subquery. Using EXISTS is helpful when you need to have it as a part of a bigger query. But if you just want to check from your Laravel app if record exists, Eloquent provides simpler way to do this:

正如mysql 文档所建议的, EXISTS 仍将执行提供的子查询。当您需要将 EXISTS 作为更大查询的一部分时,使用 EXISTS 会很有帮助。但是如果你只是想从你的 Laravel 应用程序中检查记录是否存在,Eloquent 提供了更简单的方法来做到这一点:

DB::table('table_name')->where('field_name', 'value')->exists();

this will execute query like

这将执行查询

select count(*) as aggregate from `table_name` where `field_name` = 'value' limit 1
// this is kinda the same as your subquery for EXISTS

and will evaluate the result and return a true/false depending if record exists.

并将评估结果并根据记录是否存在返回真/假。

For me this way is also cleaner then the accepted answer, because it's not using raw queries.

对我来说,这种方式也比接受的答案更清晰,因为它没有使用原始查询。

Update

更新

In laravel 5 the same statement will now execute

在 laravel 5 中,现在将执行相同的语句

select exists(select * from `table_name` where `field_name` = 'value')

Which is exactly, what was asked for.

这正是所要求的。