Uniqueness in Fuel Models

As a part of broadening my horizons, I’m back to working with Fuel, a framework that has a familiar feel to some of the ones I’ve used in the past but has some extra “oomf” from new features and PHP 5.3-ness.

I was working in my models the other day and had a need for uniqueness – I wanted to be sure that the object I was pushing into the database didn’t match any other one. I went through the docs and didn’t see anything about it and a glance through the source didn’t turn up anything either. So, as an alternative, I came up with a method I put in my base model:

[php]
class Model_Base extends OrmModel
{
public function isUnique($modelObject)
{
$modelType = get_class($modelObject);
$found = $modelType::find(‘all’,array(
‘where’ => $modelObject->to_array()
));
return (count($found)>0) ? false : true;
}
}
[/php]

The code above finds the class name (the model the object is made from) and tries to find anything with exactly the same properties. The “to_array()” method is something Fuel has to translate objects into handy arrays.

Fuel ORM docs

Advertisement

2 comments

  1. So you fetch whole record matching given conditions in order to check whether it exists? Why don`t you use “count()” or “exists()” DB procedureso or just fetch one column instead? And if you use this method to determine whether insert or update it would be much better to write your own procedure and handle that case in database using unique constraint.

    Regards

    Micha?

    Like

  2. Good point on both – I think it could be pretty easily changed to use a count instead. As far as the unique constraint, I hand’t thought about that. I’m not 100% sure I don’t want conditionals in there though.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s