File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed
src/Illuminate/Database/Eloquent Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change @@ -157,6 +157,13 @@ class Builder implements BuilderContract
157
157
*/
158
158
protected $ afterQueryCallbacks = [];
159
159
160
+ /**
161
+ * The callbacks that should be invoked on clone.
162
+ *
163
+ * @var array
164
+ */
165
+ protected $ onCloneCallbacks = [];
166
+
160
167
/**
161
168
* Create a new Eloquent query builder instance.
162
169
*
@@ -2170,6 +2177,19 @@ public function clone()
2170
2177
return clone $ this ;
2171
2178
}
2172
2179
2180
+ /**
2181
+ * Register a closure to be invoked on a clone.
2182
+ *
2183
+ * @param \Closure $callback
2184
+ * @return $this
2185
+ */
2186
+ public function onClone (Closure $ callback )
2187
+ {
2188
+ $ this ->onCloneCallbacks [] = $ callback ;
2189
+
2190
+ return $ this ;
2191
+ }
2192
+
2173
2193
/**
2174
2194
* Force a clone of the underlying query builder when cloning.
2175
2195
*
@@ -2178,5 +2198,9 @@ public function clone()
2178
2198
public function __clone ()
2179
2199
{
2180
2200
$ this ->query = clone $ this ->query ;
2201
+
2202
+ foreach ($ this ->onCloneCallbacks as $ onCloneCallback ) {
2203
+ $ onCloneCallback ($ this );
2204
+ }
2181
2205
}
2182
2206
}
Original file line number Diff line number Diff line change @@ -2485,6 +2485,32 @@ public function testClone()
2485
2485
$ this ->assertSame ('select * from "users" where "email" = ? ' , $ clone ->toSql ());
2486
2486
}
2487
2487
2488
+ public function testCloneModelMakesAFreshCopyOfTheModel ()
2489
+ {
2490
+ $ query = new BaseBuilder (m::mock (ConnectionInterface::class), new Grammar , m::mock (Processor::class));
2491
+ $ builder = (new Builder ($ query ))->setModel (new EloquentBuilderTestStub );
2492
+ $ builder ->select ('* ' )->from ('users ' );
2493
+
2494
+ $ onCloneCallbackCalledCount = 0 ;
2495
+
2496
+ $ onCloneQuery = null ;
2497
+
2498
+ $ builder ->onClone (function (Builder $ query ) use (&$ onCloneCallbackCalledCount , &$ onCloneQuery ) {
2499
+ $ onCloneCallbackCalledCount ++;
2500
+
2501
+ $ onCloneQuery = $ query ;
2502
+ });
2503
+
2504
+ $ clone = $ builder ->clone ()->where ('email ' , 'foo ' );
2505
+
2506
+ $ this ->assertNotSame ($ builder , $ clone );
2507
+ $ this ->assertSame ('select * from "users" ' , $ builder ->toSql ());
2508
+ $ this ->assertSame ('select * from "users" where "email" = ? ' , $ clone ->toSql ());
2509
+
2510
+ $ this ->assertSame (1 , $ onCloneCallbackCalledCount );
2511
+ $ this ->assertSame ($ onCloneQuery , $ clone );
2512
+ }
2513
+
2488
2514
public function testToRawSql ()
2489
2515
{
2490
2516
$ query = m::mock (BaseBuilder::class);
You can’t perform that action at this time.
0 commit comments