Skip to content

Commit

Permalink
Adds deferred binding support to ensureAttachOneIsSingular
Browse files Browse the repository at this point in the history
This is based on non-deferred logic and ensures deferred singular stacked file uploads remain singular
  • Loading branch information
octoberapp committed Sep 7, 2023
1 parent e9831f0 commit c495714
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions src/Database/Relations/AttachOneOrMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,21 +110,19 @@ public function addEagerConstraints(array $models)
*/
public function save(Model $model, $sessionKey = null)
{
if ($sessionKey === null) {
$this->ensureAttachOneIsSingular();
}

if (!array_key_exists('is_public', $model->attributes)) {
$model->setAttribute('is_public', $this->isPublic());
}

$model->setAttribute('field', $this->relationName);

if ($sessionKey === null) {
$this->ensureAttachOneIsSingular();
return parent::save($model);
}

$this->add($model, $sessionKey);

return $model->save() ? $model : false;
}

Expand All @@ -133,16 +131,16 @@ public function save(Model $model, $sessionKey = null)
*/
public function create(array $attributes = [], $sessionKey = null)
{
if ($sessionKey === null) {
$this->ensureAttachOneIsSingular();
}

if (!array_key_exists('is_public', $attributes)) {
$attributes = array_merge(['is_public' => $this->isPublic()], $attributes);
}

$attributes['field'] = $this->relationName;

if ($sessionKey === null) {
$this->ensureAttachOneIsSingular();
}

$model = parent::create($attributes);

if ($sessionKey !== null) {
Expand Down Expand Up @@ -221,6 +219,7 @@ public function add(Model $model, $sessionKey = null)
$this->parent->fireEvent('model.relation.add', [$this->relationName, $model]);
}
else {
$this->ensureAttachOneIsSingular($sessionKey);
$this->parent->bindDeferred($this->relationName, $model, $sessionKey);
}
}
Expand Down Expand Up @@ -319,9 +318,20 @@ protected function isModelRemovable($model): bool
* ensureAttachOneIsSingular ensures AttachOne only has one attachment,
* by deleting siblings for singular relations.
*/
protected function ensureAttachOneIsSingular()
protected function ensureAttachOneIsSingular($sessionKey = null)
{
if ($this instanceof AttachOne && $this->parent->exists) {
if (!$this instanceof AttachOne) {
return;
}

if ($sessionKey) {
foreach ($this->withDeferred($sessionKey)->get() as $record) {
$this->parent->unbindDeferred($this->relationName, $record, $sessionKey);
}
return;
}

if ($this->parent->exists) {
$this->delete();
}
}
Expand Down

0 comments on commit c495714

Please sign in to comment.