Laravel eloquent 返回内容的速度和数量差异很大

Laravel eloquent big difference in speed and amount of content returned

我一直在测试 Laravel,我 运行 以下查询:

 $site = Sites::where('url', '=', Request::server('HTTP_HOST'));

数据库只包含 1 条记录,我 var_dump $site 得到类似于下面的输出,只是返回了将近 900,000 个字符。

如果我保持查询简单,例如:

$site = Sites::all();

输出是:

object(Illuminate\Database\Eloquent\Collection)#121 (1) { ["items":protected]=> array(1) { [0]=> object(App\Sites)#122 (26) { ["connection":protected]=> string(5) "mysql" ["table":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["keyType":protected]=> string(3) "int" ["incrementing"]=> bool(true) ["with":protected]=> array(0) { } ["withCount":protected]=> array(0) { } ["perPage":protected]=> int(15) ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) ["attributes":protected]=> array(9) { ["id"]=> int(75) ["name"]=> string(4) "test" ["url"]=> string(7) "test.oo" ["site_type"]=> string(4) "CASH" ["active"]=> int(1) ["site_vat"]=> string(6) "20.000" ["theme"]=> string(4) "test" ["api"]=> string(8) "test.php" ["order_prepend"]=> string(4) "TEST" } ["original":protected]=> array(9) { ["id"]=> int(75) ["name"]=> string(4) "test" ["url"]=> string(7) "test.oo" ["site_type"]=> string(4) "CASH" ["active"]=> int(1) ["site_vat"]=> string(6) "20.000" ["theme"]=> string(4) "test" ["api"]=> string(8) "test.php" ["order_prepend"]=> string(4) "TEST" } ["changes":protected]=> array(0) { } ["casts":protected]=> array(0) { } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["appends":protected]=> array(0) { } ["dispatchesEvents":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["relations":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["timestamps"]=> bool(true) ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } } } }

相当少(1,600 个字符),当 运行 第一个查询很慢时的性能,我是不是做错了什么,因为我担心性能(为什么第一个查询这么慢)。

谢谢

在第一个实例中,您 return 创建一个查询构建器实例,而在第二个实例中,您实际上 return 使用集合。

即第一个查询不会 return 任何实际数据,而是一种检索数据的方法,而第二个查询确实会获取数据。

如果您希望第一个查询 return 数据并减少输出大小和时间,您需要在查询末尾添加 ->get() 以实际执行查询。

使用 .get() 方法将结果检索为 collection 对象:

$site = Sites::where('url', '=', Request::server('HTTP_HOST'))->get()[0];

或使用 .first() 方法获取第一个与您的查询匹配的模型对象:

$site = Sites::where('url', '=', Request::server('HTTP_HOST'))->first();