diff --git a/src/Phaseolies/Database/Entity/Model.php b/src/Phaseolies/Database/Entity/Model.php index 98acec4..0fb25ed 100644 --- a/src/Phaseolies/Database/Entity/Model.php +++ b/src/Phaseolies/Database/Entity/Model.php @@ -1017,14 +1017,15 @@ public function toArray(): array $attributes = $this->makeVisible(); foreach ($this->relations as $key => $relation) { - if ($relation instanceof Model) { + if ($relation === null) { + $attributes[$key] = null; + } elseif ($relation instanceof Model) { $attributes[$key] = $relation->toArray(); } elseif ($relation instanceof Collection) { $attributes[$key] = $relation->map(function ($item) { $result = $item instanceof Model ? $item->toArray() : (array)$item; - if (isset($item->pivot_data)) { - $result['pivot'] = (array)$item->pivot_data; - unset($result['pivot_data']); + if (isset($item->pivot)) { + $result['pivot'] = (array)$item->pivot; } return $result; })->all(); diff --git a/src/Phaseolies/Database/Entity/Query/InteractsWithModelQueryProcessing.php b/src/Phaseolies/Database/Entity/Query/InteractsWithModelQueryProcessing.php index 2eaef44..ce2410c 100644 --- a/src/Phaseolies/Database/Entity/Query/InteractsWithModelQueryProcessing.php +++ b/src/Phaseolies/Database/Entity/Query/InteractsWithModelQueryProcessing.php @@ -105,31 +105,6 @@ public static function count(): int return static::query()->count(); } - /** - * Converts the model's attributes to an array. - * - * @return array. - */ - public function toArray(): array - { - $attributes = $this->makeVisible(); - - // Include loaded relationships - foreach ($this->relations as $key => $relation) { - if ($relation === null) { - $attributes[$key] = null; - } elseif ($relation instanceof Model) { - $attributes[$key] = $relation->toArray(); - } elseif ($relation instanceof Collection) { - $attributes[$key] = $relation->all(); - } else { - $attributes[$key] = $relation; - } - } - - return $attributes; - } - /** * Pluck an array of values from a single column. * @@ -265,7 +240,7 @@ public function getDirtyAttributes(): array foreach ($this->attributes as $key => $value) { if ( !array_key_exists($key, $this->originalAttributes) || - $this->originalAttributes[$key] != $value + !$this->valuesAreEqual($this->originalAttributes[$key], $value) ) { $dirty[$key] = $value; } @@ -274,6 +249,21 @@ public function getDirtyAttributes(): array return $dirty; } + /** + * Compare original and current values for equality, treating nulls as equal + * + * @param mixed $original + * @param mixed $current + * @return bool + */ + protected function valuesAreEqual(mixed $original, mixed $current): bool + { + if ($original === null && $current === null) return true; + if ($original === null || $current === null) return false; + + return (string)$original === (string)$current; + } + /** * Insert multiple records into the database *