BaseModel: Added findOrNew

This commit is contained in:
Igor Scheller 2018-09-25 17:29:15 +02:00 committed by msquare
parent c9afc27ab9
commit c4867811e2
2 changed files with 34 additions and 0 deletions

View File

@ -36,4 +36,16 @@ abstract class BaseModel extends Model
{
return static::query()->find($id, $columns);
}
/**
* Find a model by its attributes or create a new one
*
* @param mixed $id
* @param array $columns
* @return static|Model
*/
public static function findOrNew($id, $columns = ['*'])
{
return static::query()->findOrNew($id, $columns);
}
}

View File

@ -43,4 +43,26 @@ class BaseModelTest extends TestCase
$this->assertEquals($anotherModel, $newModel);
}
/**
* @covers \Engelsystem\Models\BaseModel::findOrNew
*/
public function testFindOrNew()
{
/** @var QueryBuilder|MockObject $queryBuilder */
$queryBuilder = $this->createMock(QueryBuilder::class);
BaseModelImplementation::$queryBuilder = $queryBuilder;
$anotherModel = new BaseModelImplementation();
$queryBuilder->expects($this->once())
->method('findOrNew')
->with(31337, ['lorem', 'ipsum'])
->willReturn($anotherModel);
$model = new BaseModelImplementation();
$newModel = $model->findOrNew(31337, ['lorem', 'ipsum']);
$this->assertEquals($anotherModel, $newModel);
}
}