Laravel:查询构建器如何处理 - > first()?

Laravel:查询构建器如何处理 - > first()?

问题描述:

How does the query builder handle ->first()?

Does it simply do a Limit 1 or does it do some advanced checking to make sure if only 1 row is returned?

In rare cases, the application may want to ensure that ONLY 1 row will be returned. Perhaps ->first() is not the best solution?

Any insight or direction is greatly appreciated!

查询构建器如何处理 - > first() code>? p>

它只是执行 Limit 1 code>还是进行一些高级检查以确定是否只返回1行? p>

In 在极少数情况下,应用程序可能希望确保仅返回1行。 也许 - > first() code>不是最佳解决方案? p>

非常感谢任何见解或方向! p> div>

The first() method will always return one result or null if no results are found. Here's all it does:

public function first($columns = array('*'))
{
    $results = $this->take(1)->get($columns);

    return count($results) > 0 ? reset($results) : null;
}

The difference to just using take(1) (or limit(1)) is that it actually just returns one result object, by calling reset(). (Also, first() obviously executes the query. The others don't)