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.
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