Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/JoinsHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ public static function ensureModelIsUniqueToQuery($query): void
// This can happen if a certain query, *before having interacted with the library
// `joinRelationship()` method*, was cloned by previous code.
$query->setModel($model = new ($query->getModel()));
$model->mergeCasts($originalModel->getCasts());

// Link the Spl Object ID of the query to the new model...
static::$modelQueryDictionary[$model] = $querySplObjectId;
Expand All @@ -98,6 +99,7 @@ public static function ensureModelIsUniqueToQuery($query): void

// Ensure the model of the cloned query is unique to the query.
$query->setModel($model = new $originalModel());
$model->mergeCasts($originalModel->getCasts());

// Update any `beforeQueryCallbacks` to link to the new `$this` as Eloquent Query,
// otherwise the reference to the current Eloquent query goes wrong. These query
Expand Down
36 changes: 36 additions & 0 deletions tests/WithCastsPreservationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace Kirschbaum\PowerJoins\Tests;

use Kirschbaum\PowerJoins\Tests\Models\User;

class WithCastsPreservationTest extends TestCase
{
/** @test */
public function test_withcasts_values_preserved_when_joining_relationship()
{
$query = User::query()
->withCasts(['created_at' => 'date:Y-m']) // Format date as year-month only
->joinRelationship('posts');

$model = $query->getModel();

$this->assertArrayHasKey('created_at', $model->getCasts());
$this->assertSame('date:Y-m', $model->getCasts()['created_at']);
}

/** @test */
public function test_withcasts_values_preserved_after_query_is_cloned()
{
$query = User::query()
->joinRelationship('posts')
->withCasts(['another_field' => 'date:Y-m']);

$clonedQuery = $query->clone();
$clonedQuery->joinRelationship('images');

$model = $clonedQuery->getModel();
$this->assertArrayHasKey('another_field', $model->getCasts());
$this->assertSame('date:Y-m', $model->getCasts()['another_field']);
}
}