views:

2374

answers:

3

Having never worked with ORM before I thought I would give it a try today, I've come across my first problem that I don't know how to solve (due to my lack of understanding how ORM really works.)

Say I have three tables: Languages, Codes, and a pivot table Codes_Languages. These all have properly defined relationships in the models.

Now, to echo all the names of the languages, I could go like this:

$languages = ORM::factory('languages')->find_all();
foreach ($languages as $language)
{
  echo $language->name, '<br />';
}

If I want to echo all the names of codes within a particular language, I could go like this:

$language = ORM::factory('languages', 1);
foreach ($language->codes as $code)
{
  echo $code->title, ' ', $code->description;
}

But how about if I need to do this: Retrieve the latest five codes (ordered by DESC on code.time_posted) in each language?

$languages = ORM::factory('languages')->find_all();
???$languages->codes = ORM->order_by('time_posted', 'desc')->limit(5);???
foreach ($languages as $language)
{
  echo $language->name, '<br />';
  foreach ($language->codes as $code)
  {
    echo $code->name, ' ', $code->description;
  }
}

I've placed question marks around some pseudo-code which I think explains what I'm trying to do. I've recently converted from CodeIngiter because I think Kohana is a bit more well thought out, however the docs seem lacking and I couldn't find out how to do what I needed.

Any guidance would be great. Thanks.

+1  A: 

Disclaimer: I've never used Kohana's ORM, but from reading the documentation, it seems like you need something like this:

ORM::factory('languages')->orderby('time_posted', 'DESC')->find_all(5);

You can use nearly all Kohana's query builder methods like orderby, join etc. on the ORM object to do more complex queries.

(As far as ORMs for PHP go, Doctrine is about as good as it gets. It should integrate nicely with Kohana, or any other framework for that matter.)

Øystein Riiser Gundersen
A: 

Hi,

ORM in Kohana only works if you follow this conditions :

  1. The table name must be in plural (like 'languages', wich you already have done);
  2. The table must have an id with auto increment (required);
  3. You must create a Model that extends ORM class (this one not in plural, 'language'), like :

    class Language_Model extends ORM { }

You can latter post some additional parameters to the class above, following kohana's documentation.

yoda
A: 

Try this:

$languages = ORM::factory('languages')->find_all();

foreach ($languages as $language)
{
  echo $language->name, '<br />';
  foreach ($language->order_by('time_posted', 'desc')->limit(5)->codes as $code)
  {
    echo $code->name, ' ', $code->description;
  }
}

I haven't tested it, but it should work; I've been using Kohana's ORM for a few weeks now.

Adam Bradley