0

I use Codeigniter with datamapper orm and have a problem

this are my models:

mailing -> has many row

row -> has many cell

cell -> has many version

version has one created and one updated field.

I want to get the last 10 mailings order by last version changes created or updated..

I thought to do it like this:

$versions = new Version();

now get last 10 versions order by created or updated

and distinct by mailing_id and now get all mailings to show... like this: ?

foreach ($version as $v) 
{
$v->mailing->get();
}

thx for helping

Community
  • 1
  • 1
John Smith
  • 47
  • 8

1 Answers1

1

Yes, you can call ->get() on every related model inside a loop but this would generate a n+1 query scenario and be slow if you are looping over lots of version rows.

You can use the include_related to get full Mailing instances loaded with data when you query Versions in one step (with a join behind a curtain) like this:

$versions = new Version;
$versions->order_by(...)->limit(...); // add your ordering and limiting as before
$versions->include_related('mailing', null, true, true);
// include related mailings, with of their fields and create instances, see
$versions->get();

foreach ($versions as $version) {
    // now the $version->mailing is a Mailing instance loaded with the related data
    print $version->mailing->id
}
Community
  • 1
  • 1
complex857
  • 20,425
  • 6
  • 51
  • 54