2

I'm having a bit of trouble trying to figure out the best way to check if a particular result contains any records for the following code:

 $record = ORM::factory('my_table', $id);

What I would normally do is use a counter method like $record->count() or $records->exist() method that would simply return true or false if anything was found. But there is not such a thing implemented for ORM.

I know kohana ORMs implements the SPL countable interface therefore I can use the php count() function, but this is really not useful when only one record is expected because count() will return 1 for any model that contains no data, for example if an id was not found.

This is the way I get around it:

try {
 $record = ORM::factory('my_table', $id);

 if($record->id === NULL) {
   throw new Exception('The id: ' . $id . ' was not found, use a valid ID');
 }

}

This particular solution is not very good, what if my the table doesn't contain an id field or if the table allows IDs to be null?

There has to be a better way to check if a model contains any data or not.

Any ideas?

Onema
  • 7,331
  • 12
  • 66
  • 102

2 Answers2

4
try 
{
    $record = ORM::factory('my_table', $id);

    if ( ! $record->loaded()) 
    {
        throw new Exception('The id: ' . $id . ' was not found, use a valid ID');
    }
}

http://kohanaframework.org/3.2/guide/api/ORM#loaded

Thorsten
  • 5,634
  • 6
  • 35
  • 33
  • The sad thing is that that method is currently not documented as far as what it does... Thank you! – Onema Jul 10 '12 at 23:15
  • 3
    Kohana's lack of documentation is its biggest downfall. Who cares what the source code of the method is, just give us a decent description of the function and show us an example of how to use it. If I wasn't so far into my project already I would switch frameworks. – Gavin Aug 20 '13 at 14:28
3
$record = ORM::factory('my_table', $id);

if ($record->loaded())
{
    // Load was successful
}
else
{
    // Error
}
Jarod Law Ding Yong
  • 5,697
  • 2
  • 24
  • 16