Yii2: Create Active Record Model From Condition

Created on 15 Jun 2017  路  4Comments  路  Source: yiisoft/yii2

It will be great if we have some methods like findOneOrCreate in active record class to create new model if condition array is don't have any match.

$object = MyModel::findOneOrCreate(['name' => 'My name']);

By the way we can have some more methods like findOneOrNew to make an object if not found and findAllOrFail to raise exception if data not found.

under discussion

All 4 comments

I have added a pull request for these features.

Simple condition is 3 lines at max so doesn't worth implementing it as a shortcut. In reality, condition is usually more complicated. There could be permission checks, extra computations etc. etc. Each case is different so simple findOrNew() doesn't make much sense to me.

@yiisoft/core-developers need opinions.

findOneOrCreate in active record class to create new model if condition array is don't have any match.

I am against such change: it creates implicit program workflow, which reduces a readability. The common code for this is simple enough:

$condition = [
    'name' => 'some',
    'categoryId' => 17,
];
if (($model = Item::findOne($condition)) !== null) {
    $model = new Item($conditon);
}

I can see no reason to hide a simple if statement inside some method.

If you wish this so badly you can do it on your own:

class Item extends \yii\db\ActiveRecord
{
    public static function findOneOrCreate($condition)
    {
        if (($model = static::findOne($condition)) !== null) {
            $model = new Item($conditon);
        }
        return $model;
    }
}

You can extract this into a trait and reuse if necessary.

findAllOrFail to raise exception if data not found.

This is already rejected, see #3896

Was this page helpful?
0 / 5 - 0 ratings

Related issues

psfpro picture psfpro  路  3Comments

MUTOgen picture MUTOgen  路  3Comments

indicalabs picture indicalabs  路  3Comments

indicalabs picture indicalabs  路  3Comments

kminooie picture kminooie  路  3Comments