File tree 2 files changed +38
-0
lines changed 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -76,6 +76,7 @@ public static function ensureModelIsUniqueToQuery($query): void
76
76
// This can happen if a certain query, *before having interacted with the library
77
77
// `joinRelationship()` method*, was cloned by previous code.
78
78
$ query ->setModel ($ model = new ($ query ->getModel ()));
79
+ $ model ->mergeCasts ($ originalModel ->getCasts ());
79
80
80
81
// Link the Spl Object ID of the query to the new model...
81
82
static ::$ modelQueryDictionary [$ model ] = $ querySplObjectId ;
@@ -98,6 +99,7 @@ public static function ensureModelIsUniqueToQuery($query): void
98
99
99
100
// Ensure the model of the cloned query is unique to the query.
100
101
$ query ->setModel ($ model = new $ originalModel ());
102
+ $ model ->mergeCasts ($ originalModel ->getCasts ());
101
103
102
104
// Update any `beforeQueryCallbacks` to link to the new `$this` as Eloquent Query,
103
105
// otherwise the reference to the current Eloquent query goes wrong. These query
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ namespace Kirschbaum \PowerJoins \Tests ;
4
+
5
+ use Kirschbaum \PowerJoins \Tests \Models \User ;
6
+
7
+ class WithCastsPreservationTest extends TestCase
8
+ {
9
+ /** @test */
10
+ public function test_withcasts_values_preserved_when_joining_relationship ()
11
+ {
12
+ $ query = User::query ()
13
+ ->withCasts (['created_at ' => 'date:Y-m ' ]) // Format date as year-month only
14
+ ->joinRelationship ('posts ' );
15
+
16
+ $ model = $ query ->getModel ();
17
+
18
+ $ this ->assertArrayHasKey ('created_at ' , $ model ->getCasts ());
19
+ $ this ->assertSame ('date:Y-m ' , $ model ->getCasts ()['created_at ' ]);
20
+ }
21
+
22
+ /** @test */
23
+ public function test_withcasts_values_preserved_after_query_is_cloned ()
24
+ {
25
+ $ query = User::query ()
26
+ ->joinRelationship ('posts ' )
27
+ ->withCasts (['another_field ' => 'date:Y-m ' ]);
28
+
29
+ $ clonedQuery = $ query ->clone ();
30
+ $ clonedQuery ->joinRelationship ('images ' );
31
+
32
+ $ model = $ clonedQuery ->getModel ();
33
+ $ this ->assertArrayHasKey ('another_field ' , $ model ->getCasts ());
34
+ $ this ->assertSame ('date:Y-m ' , $ model ->getCasts ()['another_field ' ]);
35
+ }
36
+ }
You can’t perform that action at this time.
0 commit comments