Laravel 数据库查询读取不使用 get

我花了 1 小时在谷歌上寻找这个,但我没有运气


这是我第一次使用 Laravel。我必须尝试使用数据库的基本示例。首先是我使用普通 php 的旧代码:


echo "<table border=1>";

$q="SELECT * from USERS"; 

$result = $mysqli->query($q);

while(($o = $result->fetch_object()))

{   

    echo "<tr>";

    echo "<td>$o->ID</td><td>$o->Name</td>";

    echo "</tr>";

}

echo "</table>";

现在我在 laravel 中尝试同样的方法


$query=DB::Table("users")->select("*");

我知道我可以使用


$allrows=$query->get();

这个将所有结果都放在一个数组中,但是如果您有 200 万用户,那将是一个大问题。


这个返回第一行


$Firstrow=$query->first();

我只想一行一行地获取行,比如


$query=DB::Table("users")->select("*");


while($o=$query->next())

    {   

        echo "<tr>";

        echo "<td>$o->ID</td><td>$o->Name</td>";

        echo "</tr>";

    }

也许我是错的,因为我是 Laravel 的新手,但这使用的内存更少,因为只有一个处于活动状态。


PD:我在 laravel 中看到过分页,但我只想逐行使用旧方法……如果可能的话。


提前致谢。


aluckdog
浏览 98回答 3
3回答

DIEA

对于这样的事情,您可以使用以下cursor()方法:$users = DB::table('users')->cursor();foreach ($users as $user) {&nbsp; &nbsp; echo $user->id;}如果你传递$users给刀片文件,那么你可以有以下内容<table>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; @foreach($users as $user)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>{{ $user->ID }}</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>{{ $user->Name }}</td>&nbsp; &nbsp; &nbsp; &nbsp; @endforeach&nbsp; &nbsp; </tr></table>

芜湖不芜

您应该使用游标方法而不是 get() 函数。因为游标方法允许您使用游标遍历数据库记录,游标只会执行一个查询。foreach (Flight::where('foo', 'bar')->cursor() as $flight) {&nbsp; &nbsp; //}参考链接:- https://laravel.com/docs/7.x/eloquent

holdtom

你可以使用 eloquent 提供的 chunks 方法。在这里阅读更多相关信息https://laraveldaily.com/process-big-db-table-with-chunk-method/DB::table('users')->chunk(100, function($users){&nbsp; &nbsp; foreach ($users as $user)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //do something&nbsp; &nbsp; }});
打开App,查看更多内容
随时随地看视频慕课网APP