How to get database resource instead of array from Laravel Query Builder?

When I execute the PDO statement, the internal result set is saved, and I can use ->fetch()to get the string from the result.

If I wanted to convert the whole result into an array, I could do it ->fetchAll().

With Laravel's Query Builder Docs , I only see a way to get the result of an array from executing a query.

// example query, ~30,000 rows

$scores = DB::table("highscores")
            ->select("player_id", "score")
            ->orderBy("score", "desc")
            ->get();

var_dump($scores);
// array of 30,000 items...
// unbelievable ...

Is there a way to get a result set from Query Builder like PDO? Or am I forced to wait for Query Builder to build an entire array before it returns a value?

Perhaps something like ->lazyGet()or ->getCursor()?


, , Query Builder . , 30 000 . PDO , ->fetch() , .

Laravel Query Builder ? " , ? , 30 000 !"


PS , , ->skip() ->take() . , 30 000 . , , PHP .

+4
3

, @deczo ->chunk(), . , ->chunk() - , , ->step($m)->take($n). , ->chunk , 30 000 1.

, ->chunk() , . - , , .

, , Query Builder \Illuminate\Database\Connection # run.

// https://github.com/laravel/framework/blob/3d1b38557afe0d09326d0b5a9ff6b5705bc67d29/src/Illuminate/Database/Connection.php#L262-L284

/**
 * Run a select statement against the database.
 *
 * @param  string  $query
 * @param  array   $bindings
 * @return array
 */
public function select($query, $bindings = array())
{
  return $this->run($query, $bindings, function($me, $query, $bindings)
  {
    if ($me->pretending()) return array();

    // For select statements, we'll simply execute the query and return an array
    // of the database result set. Each element in the array will be a single
    // row from the database table, and will either be an array or objects.
    $statement = $me->getReadPdo()->prepare($query);

    $statement->execute($me->prepareBindings($bindings));

    return $statement->fetchAll($me->getFetchMode());
  });
}

, $statement->fetchAll ?

, ; Laravel Query Builder.

.


, , , Laravel , , . !

+4

chunk:

DB::table('highscores')
   ->select(...)
   ->orderBy(...)
   ->chunk($rowsNumber, function ($portion) {
      foreach ($portion as $row) { // do whatever you like }
   });

, , get, :

$portion; // array of stdObjects

// and for Eloquent models:
Model::chunk(100, function ($portion) {
    $portion; // Collection of Models
});
+3

laravel , pdo- , , , - , 30- .

, laravel, pdo.

, , , ( pdo), , .

$qb = DB::table("highscores")
        ->select("player_id", "score")
        ->orderBy("score", "desc");

$connection = $qb->getConnection();

$pdo = $connection->getPdo();

$query = $qb->toSql();
$bindings = $qb->getBindings();

$statement = $pdo->prepare($query);
$statement->execute($bindings);

while ($row = $statement->fetch($connection->getFetchMode()))
{
    // do stuff with $row
}
+2
source

Source: https://habr.com/ru/post/1547966/


All Articles