idiorm database request outside of foreach loop

240 Views Asked by At

I was told that database request make in loop (foreach) is bad, but how can I do other way this request:

$k1 = ORM::for_table('k1')->find_many();
foreach($k1 as $k){
    $k2 = ORM::for_table('k2')->where('id', $k->id)->find_one();
    echo $k2->name;
}
1

There are 1 best solutions below

2
Davide Pastore On BEST ANSWER

Using the join you can create the same query without use a loop.

Edit after the comment:

<?php
$results = ORM::for_table('k1')
    ->select('k2.*')
    ->join('k1_to_k2', array('k1.id', '=', 'k1_to_k2.k1_id'))
    ->join('k2', array('k1.id', '=', 'k2.id'))
    ->find_many();

foreach($results as $result){
  echo $result->name;
}

Previous answer:

<?php
$results = ORM::for_table('k1')
    ->select('k2.*')
    ->join('k2', array('k1.id', '=', 'k2.id'))
    ->find_many();

foreach($results as $result){
  echo $result->name;
}