summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/Models/BaseModel.php12
-rw-r--r--tests/Unit/Models/BaseModelTest.php22
2 files changed, 34 insertions, 0 deletions
diff --git a/src/Models/BaseModel.php b/src/Models/BaseModel.php
index d5ded428..2367f5b6 100644
--- a/src/Models/BaseModel.php
+++ b/src/Models/BaseModel.php
@@ -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);
+ }
}
diff --git a/tests/Unit/Models/BaseModelTest.php b/tests/Unit/Models/BaseModelTest.php
index 9af55fa1..963ea64a 100644
--- a/tests/Unit/Models/BaseModelTest.php
+++ b/tests/Unit/Models/BaseModelTest.php
@@ -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);
+ }
}