我一直在测试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){ ["项目":保护] => array(1){[0] => object(App \ Sites)#122(26){ ["连接":保护] => string(5)" mysql" ["表":保护] => NULL [" primaryKey":protected] => string(2)" id" ["关键字类型":保护] => string(3)" int" ["递增"] => bool(true)[" with":protected] => array(0){} [" withCount":protected] =>数组(0){} [" perPage":保护] => int(15)["存在"] =>布尔(真) [" wasRecentlyCreated"] => bool(false)[" attributes":protected] => array(9){[" id"] => int(75)[" name"] => string(4)" test" [" URL"] => string(7)" test.oo" [" site_type"] => string(4)"现金" ["有源"] => int(1)[" site_vat"] => string(6)" 20.000" ["主题"] => string(4)" test" [" API"] => string(8)" test.php" [" order_prepend"] => string(4)" TEST" } ["原":保护] => array(9){[" id"] => int(75)[" name"] => string(4)" test" [" URL"] => string(7)" test.oo" [" site_type"] => string(4)"现金" ["有源"] => int(1)[" site_vat"] => string(6)" 20.000" ["主题"] => string(4)" test" [" API"] => string(8)" test.php" [" order_prepend"] => string(4)" TEST" } ["更改":protected] => array(0){} [" casts":protected] => array(0){} [" dates":protected] => array(0){} [" dateFormat":protected] => NULL ["追加":protected] => array(0){} [" dispatchesEvents":protected] =>数组(0){} ["观测量":保护] => array(0){} [" relations":protected] => array(0){} [" touches":protected] => array(0){} [" timestamps"] => bool(true)[" hidden":protected] => array(0){} [" visible":protected] => array(0){} [" fillable":protected] =>数组(0){} ["防护":保护] => array(1){[0] => string(1)" *" }}}
哪个少得多(1,600个字符),运行第一个查询时的性能很慢,我做错了,因为我担心性能(为什么第一个查询这么慢)。
由于
答案 0 :(得分:0)
在第一个实例上,您将返回一个查询构建器实例,在第二个实例中,您实际上正在返回该集合。
即。第一个查询不会返回任何实际数据,而是在第二个查询获取数据时检索数据的方法。
如果您希望第一个查询返回数据并减少输出大小和时间,则需要在查询末尾添加->get()
以实际执行查询。
答案 1 :(得分:0)
使用.get()
方法将结果检索为collection对象:
$site = Sites::where('url', '=', Request::server('HTTP_HOST'))->get()[0];
或使用.first()
方法获取与您的查询匹配的第一个模型对象:
$site = Sites::where('url', '=', Request::server('HTTP_HOST'))->first();