Add "by Example" Methods

Hi all,

I was wondering if there is something planned like "find by example" or "delete by example".


$user = User::model();

$user->name = 'nomar'


results in

DELETE FROM user WHERE name = 'nomar';


$user = User::model();

$user->name = 'nomar'


results in

SELECT * FROM user WHERE name = 'nomar';

So, basically the models properties are populated with more sensible values then in the example and then you could just delete or search.

The search feature is somehow implemented afaik - but returns a CActiveDataProvider instead of an array with all results.

IMHO this would make searching and deleting much more elegant - I have a hard time writing findByAttributes(…);

The code gets really unreadable if you are searching for more then one attribute.

On top of this mighty AR-Framework it should be really easy to implement.

What do you think?


I wrote my suggested methods for one of my models an it does not feel right.

Creating an Object for this operation is strange, and handling the results is also not so nice, espacially when searching - deleting is ok with me.

Maybe something like

$users = User::findByExample(array('name' => 'nomar'));

User::deleteByExample(array('name' => 'nomar'));

would be better.

And the possibility to pass in an real model instead of an array :wink:

You already have this functions, just with a differenant names: findByAttributes(findAllByAttributes), and deleteAllByAttributes().

They do exactly same thing like you request, but have better name :)

Problem: how would you distinguish unset attributes (shouldn’t generate any condition) from ones that are set to NULL explicitly (should generate an IS NULL condition)?

Yeah, you are both right.

I was mislead by the guide stating that find-methods need to be written like

$post=Post::model()->find('postID=:postID', array(':postID'=>10));

Which is really a lot to write compared with key/value

$post=Post::model()->findByAttributes(array('postID' => 10));

And I also have no solution for properties not set. They should be excluded I think, making a search for NULL values impossible.