Skip to content

Commit d7177fe

Browse files
author
David Nahodyl
committed
added auto-refresh on insert, added refresh functionality
1 parent d002c5d commit d7177fe

File tree

1 file changed

+40
-4
lines changed

1 file changed

+40
-4
lines changed

src/Database/Eloquent/FMModel.php

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
use BlueFeather\EloquentFileMaker\Database\Query\FMBaseBuilder;
77
use Illuminate\Database\Eloquent\Builder;
88
use Illuminate\Database\Eloquent\Model;
9+
use Illuminate\Database\Eloquent\Relations\Concerns\AsPivot;
10+
use Illuminate\Database\Eloquent\Relations\Pivot;
911
use Illuminate\Http\File;
1012
use Illuminate\Support\Collection;
1113
use Illuminate\Support\Str;
@@ -335,16 +337,25 @@ protected function performInsert(Builder $query)
335337
// If the model has an incrementing key, we can use the "insertGetId" method on
336338
// the query builder, which will give us back the final inserted ID for this
337339
// table from the database. Not all tables have to be incrementing though.
338-
$attributes = $this->getAttributes();
340+
$attributes = $this->getAttributesForInsert();
341+
342+
if ($this->getIncrementing()) {
343+
$query->createRecord();
344+
// perform a refresh after the insert to get the generated primary key / ID and calculated data
345+
$this->refresh();
346+
}
339347

340348
// If the table isn't incrementing we'll simply insert these attributes as they
341349
// are. These attribute arrays must contain an "id" column previously placed
342350
// there by the developer as the manually determined key for these models.
343-
if (empty($attributes)) {
344-
return true;
351+
else {
352+
if (empty($attributes)) {
353+
return true;
354+
}
355+
356+
$query->createRecord();
345357
}
346358

347-
$query->createRecord();
348359

349360

350361
// We will go ahead and set the exists property to true, so that it is set when
@@ -493,5 +504,30 @@ public function qualifyColumn($column)
493504
// so just return without the table
494505
return $column;
495506
}
507+
/**
508+
* Reload the current model instance with fresh attributes from the database.
509+
*
510+
* @return $this
511+
*/
512+
public function refresh()
513+
{
514+
// make sure we have a FileMaker internal recordId
515+
if ($this->recordId === null) {
516+
return $this;
517+
}
518+
519+
$this->setRawAttributes(
520+
$this->findByRecordId($this->recordId)->attributes
521+
);
522+
523+
$this->load(collect($this->relations)->reject(function ($relation) {
524+
return $relation instanceof Pivot
525+
|| (is_object($relation) && in_array(AsPivot::class, class_uses_recursive($relation), true));
526+
})->keys()->all());
527+
528+
$this->syncOriginal();
529+
530+
return $this;
531+
}
496532

497533
}

0 commit comments

Comments
 (0)