Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

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

if ($record->loaded())
{
    // Load was successful
}
else
{
    // Error
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top