diff --git a/src/Sushi.php b/src/Sushi.php index 043a824..0c9b941 100644 --- a/src/Sushi.php +++ b/src/Sushi.php @@ -133,18 +133,18 @@ public function migrate() $this->createTableWithNoData($tableName); } - if (count($this->casts) === 0) { + if (count($this->casts) > 0) { + foreach ($rows as $row) { + // If $casts are present, use Eloquent's "create" instead of a plain insert so they are used and applied... + static::forceCreate($row); + } + } else { foreach (array_chunk($rows, $this->getSushiInsertChunkSize()) ?? [] as $inserts) { - if (!empty($inserts)) { + if (! empty($inserts)) { static::insert($inserts); } } - } else { //casts are necessary, create each model singly so Eloquent can cast attributes as necessary - foreach ($rows as $row) { - static::create($row); - } } - } public function createTable(string $tableName, $firstRow) diff --git a/tests/SushiTest.php b/tests/SushiTest.php index 6d16159..aad9b73 100644 --- a/tests/SushiTest.php +++ b/tests/SushiTest.php @@ -60,6 +60,15 @@ function columns_with_varying_types() $this->assertEquals(null, $row->null); } + /** @test */ + function model_with_casts() + { + $model = ModelWithCasts::first(); + + $this->assertTrue(is_array($model->is_array)); + $this->assertTrue(is_bool($model->is_boolean)); + } + /** @test */ function model_with_custom_schema() { @@ -373,3 +382,18 @@ public function maki() return $this->belongsTo(Maki::class); } } + + +class ModelWithCasts extends Model +{ + use \Sushi\Sushi; + + protected $casts = [ + 'is_array' => 'array', + 'is_boolean' => 'boolean', + ]; + + protected $rows = [ + ['is_array' => [1, 2, 3], 'is_boolean' => true], + ]; +}