ActiveRecordTestTrait.php 38.7 KB
Newer Older
1 2
<?php
/**
3 4
 *
 *
5 6 7 8 9
 * @author Carsten Brandt <mail@cebe.cc>
 */

namespace yiiunit\framework\ar;

10
use yii\base\Event;
11
use yii\db\ActiveQueryInterface;
12
use yii\db\BaseActiveRecord;
13 14 15 16 17
use yiiunit\TestCase;
use yiiunit\data\ar\Customer;
use yiiunit\data\ar\Order;

/**
Qiang Xue committed
18
 * This trait provides unit tests shared by the different AR implementations
19 20 21 22 23
 *
 * @var TestCase $this
 */
trait ActiveRecordTestTrait
{
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    /**
     * This method should return the classname of Customer class
     * @return string
     */
    abstract public function getCustomerClass();

    /**
     * This method should return the classname of Order class
     * @return string
     */
    abstract public function getOrderClass();

    /**
     * This method should return the classname of OrderItem class
     * @return string
     */
    abstract public function getOrderItemClass();

    /**
     * This method should return the classname of Item class
     * @return string
     */
    abstract public function getItemClass();

    /**
     * can be overridden to do things after save()
     */
    public function afterSave()
    {
    }

    public function testFind()
    {
Qiang Xue committed
57
        /** @var \yii\db\ActiveRecordInterface $customerClass */
58 59 60
        $customerClass = $this->getCustomerClass();
        /** @var TestCase|ActiveRecordTestTrait $this */
        // find one
Qiang Xue committed
61
        $result = $customerClass::find();
62 63 64 65 66
        $this->assertTrue($result instanceof ActiveQueryInterface);
        $customer = $result->one();
        $this->assertTrue($customer instanceof $customerClass);

        // find all
Qiang Xue committed
67
        $customers = $customerClass::find()->all();
68 69 70 71 72 73
        $this->assertEquals(3, count($customers));
        $this->assertTrue($customers[0] instanceof $customerClass);
        $this->assertTrue($customers[1] instanceof $customerClass);
        $this->assertTrue($customers[2] instanceof $customerClass);

        // find all asArray
Qiang Xue committed
74
        $customers = $customerClass::find()->asArray()->all();
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
        $this->assertEquals(3, count($customers));
        $this->assertArrayHasKey('id', $customers[0]);
        $this->assertArrayHasKey('name', $customers[0]);
        $this->assertArrayHasKey('email', $customers[0]);
        $this->assertArrayHasKey('address', $customers[0]);
        $this->assertArrayHasKey('status', $customers[0]);
        $this->assertArrayHasKey('id', $customers[1]);
        $this->assertArrayHasKey('name', $customers[1]);
        $this->assertArrayHasKey('email', $customers[1]);
        $this->assertArrayHasKey('address', $customers[1]);
        $this->assertArrayHasKey('status', $customers[1]);
        $this->assertArrayHasKey('id', $customers[2]);
        $this->assertArrayHasKey('name', $customers[2]);
        $this->assertArrayHasKey('email', $customers[2]);
        $this->assertArrayHasKey('address', $customers[2]);
        $this->assertArrayHasKey('status', $customers[2]);

        // find by a single primary key
Alexander Makarov committed
93
        $customer = $customerClass::findOne(2);
94 95
        $this->assertTrue($customer instanceof $customerClass);
        $this->assertEquals('user2', $customer->name);
Alexander Makarov committed
96
        $customer = $customerClass::findOne(5);
97
        $this->assertNull($customer);
Alexander Makarov committed
98
        $customer = $customerClass::findOne(['id' => [5, 6, 1]]);
99
        $this->assertEquals(1, count($customer));
Qiang Xue committed
100
        $customer = $customerClass::find()->where(['id' => [5, 6, 1]])->one();
101 102 103
        $this->assertNotNull($customer);

        // find by column values
Alexander Makarov committed
104
        $customer = $customerClass::findOne(['id' => 2, 'name' => 'user2']);
105 106
        $this->assertTrue($customer instanceof $customerClass);
        $this->assertEquals('user2', $customer->name);
Alexander Makarov committed
107
        $customer = $customerClass::findOne(['id' => 2, 'name' => 'user1']);
108
        $this->assertNull($customer);
Alexander Makarov committed
109
        $customer = $customerClass::findOne(['id' => 5]);
110
        $this->assertNull($customer);
Alexander Makarov committed
111
        $customer = $customerClass::findOne(['name' => 'user5']);
112 113 114
        $this->assertNull($customer);

        // find by attributes
Qiang Xue committed
115
        $customer = $customerClass::find()->where(['name' => 'user2'])->one();
116 117 118 119
        $this->assertTrue($customer instanceof $customerClass);
        $this->assertEquals(2, $customer->id);

        // scope
Qiang Xue committed
120 121
        $this->assertEquals(2, count($customerClass::find()->active()->all()));
        $this->assertEquals(2, $customerClass::find()->active()->count());
122 123 124 125
    }

    public function testFindAsArray()
    {
Qiang Xue committed
126 127 128
        /** @var \yii\db\ActiveRecordInterface $customerClass */
        $customerClass = $this->getCustomerClass();

129
        // asArray
Qiang Xue committed
130
        $customer = $customerClass::find()->where(['id' => 2])->asArray()->one();
131 132 133 134 135 136 137 138 139 140 141 142
        $this->assertEquals([
            'id' => 2,
            'email' => 'user2@example.com',
            'name' => 'user2',
            'address' => 'address2',
            'status' => 1,
            'profile_id' => null,
        ], $customer);
    }

    public function testFindScalar()
    {
Qiang Xue committed
143 144 145
        /** @var \yii\db\ActiveRecordInterface $customerClass */
        $customerClass = $this->getCustomerClass();

146 147
        /** @var TestCase|ActiveRecordTestTrait $this */
        // query scalar
Qiang Xue committed
148
        $customerName = $customerClass::find()->where(['id' => 2])->scalar('name');
149
        $this->assertEquals('user2', $customerName);
Qiang Xue committed
150
        $customerName = $customerClass::find()->where(['status' => 2])->scalar('name');
151
        $this->assertEquals('user3', $customerName);
Qiang Xue committed
152
        $customerName = $customerClass::find()->where(['status' => 2])->scalar('noname');
153
        $this->assertNull($customerName);
Qiang Xue committed
154
        $customerId = $customerClass::find()->where(['status' => 2])->scalar('id');
155 156 157 158 159
        $this->assertEquals(3, $customerId);
    }

    public function testFindColumn()
    {
Qiang Xue committed
160 161 162
        /** @var \yii\db\ActiveRecordInterface $customerClass */
        $customerClass = $this->getCustomerClass();

163
        /** @var TestCase|ActiveRecordTestTrait $this */
Qiang Xue committed
164 165
        $this->assertEquals(['user1', 'user2', 'user3'], $customerClass::find()->orderBy(['name' => SORT_ASC])->column('name'));
        $this->assertEquals(['user3', 'user2', 'user1'], $customerClass::find()->orderBy(['name' => SORT_DESC])->column('name'));
166 167 168 169
    }

    public function testFindIndexBy()
    {
Qiang Xue committed
170
        /** @var \yii\db\ActiveRecordInterface $customerClass */
171 172 173
        $customerClass = $this->getCustomerClass();
        /** @var TestCase|ActiveRecordTestTrait $this */
        // indexBy
Qiang Xue committed
174
        $customers = $customerClass::find()->indexBy('name')->orderBy('id')->all();
175 176 177 178 179 180
        $this->assertEquals(3, count($customers));
        $this->assertTrue($customers['user1'] instanceof $customerClass);
        $this->assertTrue($customers['user2'] instanceof $customerClass);
        $this->assertTrue($customers['user3'] instanceof $customerClass);

        // indexBy callable
Qiang Xue committed
181
        $customers = $customerClass::find()->indexBy(function ($customer) {
182 183 184 185 186 187 188 189 190 191
            return $customer->id . '-' . $customer->name;
        })->orderBy('id')->all();
        $this->assertEquals(3, count($customers));
        $this->assertTrue($customers['1-user1'] instanceof $customerClass);
        $this->assertTrue($customers['2-user2'] instanceof $customerClass);
        $this->assertTrue($customers['3-user3'] instanceof $customerClass);
    }

    public function testFindIndexByAsArray()
    {
Qiang Xue committed
192 193 194
        /** @var \yii\db\ActiveRecordInterface $customerClass */
        $customerClass = $this->getCustomerClass();

195 196
        /** @var TestCase|ActiveRecordTestTrait $this */
        // indexBy + asArray
Qiang Xue committed
197
        $customers = $customerClass::find()->asArray()->indexBy('name')->all();
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
        $this->assertEquals(3, count($customers));
        $this->assertArrayHasKey('id', $customers['user1']);
        $this->assertArrayHasKey('name', $customers['user1']);
        $this->assertArrayHasKey('email', $customers['user1']);
        $this->assertArrayHasKey('address', $customers['user1']);
        $this->assertArrayHasKey('status', $customers['user1']);
        $this->assertArrayHasKey('id', $customers['user2']);
        $this->assertArrayHasKey('name', $customers['user2']);
        $this->assertArrayHasKey('email', $customers['user2']);
        $this->assertArrayHasKey('address', $customers['user2']);
        $this->assertArrayHasKey('status', $customers['user2']);
        $this->assertArrayHasKey('id', $customers['user3']);
        $this->assertArrayHasKey('name', $customers['user3']);
        $this->assertArrayHasKey('email', $customers['user3']);
        $this->assertArrayHasKey('address', $customers['user3']);
        $this->assertArrayHasKey('status', $customers['user3']);

        // indexBy callable + asArray
Qiang Xue committed
216
        $customers = $customerClass::find()->indexBy(function ($customer) {
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
            return $customer['id'] . '-' . $customer['name'];
        })->asArray()->all();
        $this->assertEquals(3, count($customers));
        $this->assertArrayHasKey('id', $customers['1-user1']);
        $this->assertArrayHasKey('name', $customers['1-user1']);
        $this->assertArrayHasKey('email', $customers['1-user1']);
        $this->assertArrayHasKey('address', $customers['1-user1']);
        $this->assertArrayHasKey('status', $customers['1-user1']);
        $this->assertArrayHasKey('id', $customers['2-user2']);
        $this->assertArrayHasKey('name', $customers['2-user2']);
        $this->assertArrayHasKey('email', $customers['2-user2']);
        $this->assertArrayHasKey('address', $customers['2-user2']);
        $this->assertArrayHasKey('status', $customers['2-user2']);
        $this->assertArrayHasKey('id', $customers['3-user3']);
        $this->assertArrayHasKey('name', $customers['3-user3']);
        $this->assertArrayHasKey('email', $customers['3-user3']);
        $this->assertArrayHasKey('address', $customers['3-user3']);
        $this->assertArrayHasKey('status', $customers['3-user3']);
    }

    public function testRefresh()
    {
Qiang Xue committed
239
        /** @var \yii\db\ActiveRecordInterface $customerClass */
240 241 242 243 244
        $customerClass = $this->getCustomerClass();
        /** @var TestCase|ActiveRecordTestTrait $this */
        $customer = new $customerClass();
        $this->assertFalse($customer->refresh());

Alexander Makarov committed
245
        $customer = $customerClass::findOne(1);
246 247 248 249 250 251 252
        $customer->name = 'to be refreshed';
        $this->assertTrue($customer->refresh());
        $this->assertEquals('user1', $customer->name);
    }

    public function testEquals()
    {
Qiang Xue committed
253
        /** @var \yii\db\ActiveRecordInterface $customerClass */
254
        $customerClass = $this->getCustomerClass();
Qiang Xue committed
255
        /** @var \yii\db\ActiveRecordInterface $itemClass */
256 257 258 259 260 261 262 263 264 265 266
        $itemClass = $this->getItemClass();

        /** @var TestCase|ActiveRecordTestTrait $this */
        $customerA = new $customerClass();
        $customerB = new $customerClass();
        $this->assertFalse($customerA->equals($customerB));

        $customerA = new $customerClass();
        $customerB = new $itemClass();
        $this->assertFalse($customerA->equals($customerB));

Alexander Makarov committed
267 268
        $customerA = $customerClass::findOne(1);
        $customerB = $customerClass::findOne(2);
269 270
        $this->assertFalse($customerA->equals($customerB));

Alexander Makarov committed
271
        $customerB = $customerClass::findOne(1);
272 273
        $this->assertTrue($customerA->equals($customerB));

Alexander Makarov committed
274 275
        $customerA = $customerClass::findOne(1);
        $customerB = $itemClass::findOne(1);
276 277 278 279 280
        $this->assertFalse($customerA->equals($customerB));
    }

    public function testFindCount()
    {
Qiang Xue committed
281 282 283
        /** @var \yii\db\ActiveRecordInterface $customerClass */
        $customerClass = $this->getCustomerClass();

284
        /** @var TestCase|ActiveRecordTestTrait $this */
Qiang Xue committed
285
        $this->assertEquals(3, $customerClass::find()->count());
286

Qiang Xue committed
287 288 289 290
        $this->assertEquals(1, $customerClass::find()->where(['id' => 1])->count());
        $this->assertEquals(2, $customerClass::find()->where(['id' => [1, 2]])->count());
        $this->assertEquals(2, $customerClass::find()->where(['id' => [1, 2]])->offset(1)->count());
        $this->assertEquals(2, $customerClass::find()->where(['id' => [1, 2]])->offset(2)->count());
291 292

        // limit should have no effect on count()
Qiang Xue committed
293 294 295 296
        $this->assertEquals(3, $customerClass::find()->limit(1)->count());
        $this->assertEquals(3, $customerClass::find()->limit(2)->count());
        $this->assertEquals(3, $customerClass::find()->limit(10)->count());
        $this->assertEquals(3, $customerClass::find()->offset(2)->limit(2)->count());
297 298 299 300
    }

    public function testFindLimit()
    {
Qiang Xue committed
301 302 303
        /** @var \yii\db\ActiveRecordInterface $customerClass */
        $customerClass = $this->getCustomerClass();

304 305
        /** @var TestCase|ActiveRecordTestTrait $this */
        // all()
Qiang Xue committed
306
        $customers = $customerClass::find()->all();
307 308
        $this->assertEquals(3, count($customers));

Qiang Xue committed
309
        $customers = $customerClass::find()->orderBy('id')->limit(1)->all();
310 311 312
        $this->assertEquals(1, count($customers));
        $this->assertEquals('user1', $customers[0]->name);

Qiang Xue committed
313
        $customers = $customerClass::find()->orderBy('id')->limit(1)->offset(1)->all();
314 315 316
        $this->assertEquals(1, count($customers));
        $this->assertEquals('user2', $customers[0]->name);

Qiang Xue committed
317
        $customers = $customerClass::find()->orderBy('id')->limit(1)->offset(2)->all();
318 319 320
        $this->assertEquals(1, count($customers));
        $this->assertEquals('user3', $customers[0]->name);

Qiang Xue committed
321
        $customers = $customerClass::find()->orderBy('id')->limit(2)->offset(1)->all();
322 323 324 325
        $this->assertEquals(2, count($customers));
        $this->assertEquals('user2', $customers[0]->name);
        $this->assertEquals('user3', $customers[1]->name);

Qiang Xue committed
326
        $customers = $customerClass::find()->limit(2)->offset(3)->all();
327 328 329
        $this->assertEquals(0, count($customers));

        // one()
Qiang Xue committed
330
        $customer = $customerClass::find()->orderBy('id')->one();
331 332
        $this->assertEquals('user1', $customer->name);

Qiang Xue committed
333
        $customer = $customerClass::find()->orderBy('id')->offset(0)->one();
334 335
        $this->assertEquals('user1', $customer->name);

Qiang Xue committed
336
        $customer = $customerClass::find()->orderBy('id')->offset(1)->one();
337 338
        $this->assertEquals('user2', $customer->name);

Qiang Xue committed
339
        $customer = $customerClass::find()->orderBy('id')->offset(2)->one();
340 341
        $this->assertEquals('user3', $customer->name);

Qiang Xue committed
342
        $customer = $customerClass::find()->offset(3)->one();
343 344 345 346 347 348
        $this->assertNull($customer);

    }

    public function testFindComplexCondition()
    {
Qiang Xue committed
349 350 351
        /** @var \yii\db\ActiveRecordInterface $customerClass */
        $customerClass = $this->getCustomerClass();

352
        /** @var TestCase|ActiveRecordTestTrait $this */
Qiang Xue committed
353 354
        $this->assertEquals(2, $customerClass::find()->where(['OR', ['name' => 'user1'], ['name' => 'user2']])->count());
        $this->assertEquals(2, count($customerClass::find()->where(['OR', ['name' => 'user1'], ['name' => 'user2']])->all()));
355

Qiang Xue committed
356 357
        $this->assertEquals(2, $customerClass::find()->where(['name' => ['user1', 'user2']])->count());
        $this->assertEquals(2, count($customerClass::find()->where(['name' => ['user1', 'user2']])->all()));
358

Qiang Xue committed
359 360
        $this->assertEquals(1, $customerClass::find()->where(['AND', ['name' => ['user2', 'user3']], ['BETWEEN', 'status', 2, 4]])->count());
        $this->assertEquals(1, count($customerClass::find()->where(['AND', ['name' => ['user2', 'user3']], ['BETWEEN', 'status', 2, 4]])->all()));
361 362 363 364
    }

    public function testFindNullValues()
    {
Qiang Xue committed
365 366 367
        /** @var \yii\db\ActiveRecordInterface $customerClass */
        $customerClass = $this->getCustomerClass();

368
        /** @var TestCase|ActiveRecordTestTrait $this */
Alexander Makarov committed
369
        $customer = $customerClass::findOne(2);
370 371 372 373
        $customer->name = null;
        $customer->save(false);
        $this->afterSave();

Qiang Xue committed
374
        $result = $customerClass::find()->where(['name' => null])->all();
375 376 377 378 379 380
        $this->assertEquals(1, count($result));
        $this->assertEquals(2, reset($result)->primaryKey);
    }

    public function testExists()
    {
Qiang Xue committed
381 382 383
        /** @var \yii\db\ActiveRecordInterface $customerClass */
        $customerClass = $this->getCustomerClass();

384
        /** @var TestCase|ActiveRecordTestTrait $this */
Qiang Xue committed
385 386 387 388 389 390 391 392
        $this->assertTrue($customerClass::find()->where(['id' => 2])->exists());
        $this->assertFalse($customerClass::find()->where(['id' => 5])->exists());
        $this->assertTrue($customerClass::find()->where(['name' => 'user1'])->exists());
        $this->assertFalse($customerClass::find()->where(['name' => 'user5'])->exists());

        $this->assertTrue($customerClass::find()->where(['id' => [2, 3]])->exists());
        $this->assertTrue($customerClass::find()->where(['id' => [2, 3]])->offset(1)->exists());
        $this->assertFalse($customerClass::find()->where(['id' => [2, 3]])->offset(2)->exists());
393 394 395 396
    }

    public function testFindLazy()
    {
Qiang Xue committed
397 398 399
        /** @var \yii\db\ActiveRecordInterface $customerClass */
        $customerClass = $this->getCustomerClass();

400
        /** @var TestCase|ActiveRecordTestTrait $this */
Alexander Makarov committed
401
        $customer = $customerClass::findOne(2);
402 403 404 405 406 407 408 409 410 411 412
        $this->assertFalse($customer->isRelationPopulated('orders'));
        $orders = $customer->orders;
        $this->assertTrue($customer->isRelationPopulated('orders'));
        $this->assertEquals(2, count($orders));
        $this->assertEquals(1, count($customer->relatedRecords));

        // unset
        unset($customer['orders']);
        $this->assertFalse($customer->isRelationPopulated('orders'));

        /** @var Customer $customer */
Alexander Makarov committed
413
        $customer = $customerClass::findOne(2);
414 415 416 417 418 419 420 421 422 423 424
        $this->assertFalse($customer->isRelationPopulated('orders'));
        $orders = $customer->getOrders()->where(['id' => 3])->all();
        $this->assertFalse($customer->isRelationPopulated('orders'));
        $this->assertEquals(0, count($customer->relatedRecords));

        $this->assertEquals(1, count($orders));
        $this->assertEquals(3, $orders[0]->id);
    }

    public function testFindEager()
    {
Qiang Xue committed
425 426 427 428 429
        /** @var \yii\db\ActiveRecordInterface $customerClass */
        $customerClass = $this->getCustomerClass();
        /** @var \yii\db\ActiveRecordInterface $orderClass */
        $orderClass = $this->getOrderClass();

430
        /** @var TestCase|ActiveRecordTestTrait $this */
Qiang Xue committed
431
        $customers = $customerClass::find()->with('orders')->indexBy('id')->all();
432 433 434 435 436 437 438 439 440 441 442 443
        ksort($customers);
        $this->assertEquals(3, count($customers));
        $this->assertTrue($customers[1]->isRelationPopulated('orders'));
        $this->assertTrue($customers[2]->isRelationPopulated('orders'));
        $this->assertTrue($customers[3]->isRelationPopulated('orders'));
        $this->assertEquals(1, count($customers[1]->orders));
        $this->assertEquals(2, count($customers[2]->orders));
        $this->assertEquals(0, count($customers[3]->orders));
        // unset
        unset($customers[1]->orders);
        $this->assertFalse($customers[1]->isRelationPopulated('orders'));

Qiang Xue committed
444
        $customer = $customerClass::find()->where(['id' => 1])->with('orders')->one();
445 446 447 448 449
        $this->assertTrue($customer->isRelationPopulated('orders'));
        $this->assertEquals(1, count($customer->orders));
        $this->assertEquals(1, count($customer->relatedRecords));

        // multiple with() calls
Qiang Xue committed
450
        $orders = $orderClass::find()->with('customer', 'items')->all();
451 452 453
        $this->assertEquals(3, count($orders));
        $this->assertTrue($orders[0]->isRelationPopulated('customer'));
        $this->assertTrue($orders[0]->isRelationPopulated('items'));
Qiang Xue committed
454
        $orders = $orderClass::find()->with('customer')->with('items')->all();
455 456 457 458 459 460 461
        $this->assertEquals(3, count($orders));
        $this->assertTrue($orders[0]->isRelationPopulated('customer'));
        $this->assertTrue($orders[0]->isRelationPopulated('items'));
    }

    public function testFindLazyVia()
    {
Qiang Xue committed
462 463 464
        /** @var \yii\db\ActiveRecordInterface $orderClass */
        $orderClass = $this->getOrderClass();

465 466
        /** @var TestCase|ActiveRecordTestTrait $this */
        /** @var Order $order */
Alexander Makarov committed
467
        $order = $orderClass::findOne(1);
468 469 470 471 472 473 474 475
        $this->assertEquals(1, $order->id);
        $this->assertEquals(2, count($order->items));
        $this->assertEquals(1, $order->items[0]->id);
        $this->assertEquals(2, $order->items[1]->id);
    }

    public function testFindLazyVia2()
    {
Qiang Xue committed
476 477 478
        /** @var \yii\db\ActiveRecordInterface $orderClass */
        $orderClass = $this->getOrderClass();

479 480
        /** @var TestCase|ActiveRecordTestTrait $this */
        /** @var Order $order */
Alexander Makarov committed
481
        $order = $orderClass::findOne(1);
482 483 484 485 486 487
        $order->id = 100;
        $this->assertEquals([], $order->items);
    }

    public function testFindEagerViaRelation()
    {
Qiang Xue committed
488 489 490
        /** @var \yii\db\ActiveRecordInterface $orderClass */
        $orderClass = $this->getOrderClass();

491
        /** @var TestCase|ActiveRecordTestTrait $this */
Qiang Xue committed
492
        $orders = $orderClass::find()->with('items')->orderBy('id')->all();
493 494 495 496 497 498 499 500 501 502 503
        $this->assertEquals(3, count($orders));
        $order = $orders[0];
        $this->assertEquals(1, $order->id);
        $this->assertTrue($order->isRelationPopulated('items'));
        $this->assertEquals(2, count($order->items));
        $this->assertEquals(1, $order->items[0]->id);
        $this->assertEquals(2, $order->items[1]->id);
    }

    public function testFindNestedRelation()
    {
Qiang Xue committed
504 505 506
        /** @var \yii\db\ActiveRecordInterface $customerClass */
        $customerClass = $this->getCustomerClass();

507
        /** @var TestCase|ActiveRecordTestTrait $this */
Qiang Xue committed
508
        $customers = $customerClass::find()->with('orders', 'orders.items')->indexBy('id')->all();
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
        ksort($customers);
        $this->assertEquals(3, count($customers));
        $this->assertTrue($customers[1]->isRelationPopulated('orders'));
        $this->assertTrue($customers[2]->isRelationPopulated('orders'));
        $this->assertTrue($customers[3]->isRelationPopulated('orders'));
        $this->assertEquals(1, count($customers[1]->orders));
        $this->assertEquals(2, count($customers[2]->orders));
        $this->assertEquals(0, count($customers[3]->orders));
        $this->assertTrue($customers[1]->orders[0]->isRelationPopulated('items'));
        $this->assertTrue($customers[2]->orders[0]->isRelationPopulated('items'));
        $this->assertTrue($customers[2]->orders[1]->isRelationPopulated('items'));
        $this->assertEquals(2, count($customers[1]->orders[0]->items));
        $this->assertEquals(3, count($customers[2]->orders[0]->items));
        $this->assertEquals(1, count($customers[2]->orders[1]->items));
    }

    /**
     * Ensure ActiveRelationTrait does preserve order of items on find via()
     * https://github.com/yiisoft/yii2/issues/1310
     */
    public function testFindEagerViaRelationPreserveOrder()
    {
Qiang Xue committed
531 532 533
        /** @var \yii\db\ActiveRecordInterface $orderClass */
        $orderClass = $this->getOrderClass();

534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
        /** @var TestCase|ActiveRecordTestTrait $this */

        /*
        Item (name, category_id)
        Order (customer_id, created_at, total)
        OrderItem (order_id, item_id, quantity, subtotal)

        Result should be the following:

        Order 1: 1, 1325282384, 110.0
        - orderItems:
            OrderItem: 1, 1, 1, 30.0
            OrderItem: 1, 2, 2, 40.0
        - itemsInOrder:
            Item 1: 'Agile Web Application Development with Yii1.1 and PHP5', 1
            Item 2: 'Yii 1.1 Application Development Cookbook', 1

        Order 2: 2, 1325334482, 33.0
        - orderItems:
            OrderItem: 2, 3, 1, 8.0
            OrderItem: 2, 4, 1, 10.0
            OrderItem: 2, 5, 1, 15.0
        - itemsInOrder:
            Item 5: 'Cars', 2
            Item 3: 'Ice Age', 2
            Item 4: 'Toy Story', 2
        Order 3: 2, 1325502201, 40.0
        - orderItems:
            OrderItem: 3, 2, 1, 40.0
        - itemsInOrder:
            Item 3: 'Ice Age', 2
         */
Qiang Xue committed
566
        $orders = $orderClass::find()->with('itemsInOrder1')->orderBy('created_at')->all();
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
        $this->assertEquals(3, count($orders));

        $order = $orders[0];
        $this->assertEquals(1, $order->id);
        $this->assertTrue($order->isRelationPopulated('itemsInOrder1'));
        $this->assertEquals(2, count($order->itemsInOrder1));
        $this->assertEquals(1, $order->itemsInOrder1[0]->id);
        $this->assertEquals(2, $order->itemsInOrder1[1]->id);

        $order = $orders[1];
        $this->assertEquals(2, $order->id);
        $this->assertTrue($order->isRelationPopulated('itemsInOrder1'));
        $this->assertEquals(3, count($order->itemsInOrder1));
        $this->assertEquals(5, $order->itemsInOrder1[0]->id);
        $this->assertEquals(3, $order->itemsInOrder1[1]->id);
        $this->assertEquals(4, $order->itemsInOrder1[2]->id);

        $order = $orders[2];
        $this->assertEquals(3, $order->id);
        $this->assertTrue($order->isRelationPopulated('itemsInOrder1'));
        $this->assertEquals(1, count($order->itemsInOrder1));
        $this->assertEquals(2, $order->itemsInOrder1[0]->id);
    }

    // different order in via table
    public function testFindEagerViaRelationPreserveOrderB()
    {
Qiang Xue committed
594 595 596 597
        /** @var \yii\db\ActiveRecordInterface $orderClass */
        $orderClass = $this->getOrderClass();

        $orders = $orderClass::find()->with('itemsInOrder2')->orderBy('created_at')->all();
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
        $this->assertEquals(3, count($orders));

        $order = $orders[0];
        $this->assertEquals(1, $order->id);
        $this->assertTrue($order->isRelationPopulated('itemsInOrder2'));
        $this->assertEquals(2, count($order->itemsInOrder2));
        $this->assertEquals(1, $order->itemsInOrder2[0]->id);
        $this->assertEquals(2, $order->itemsInOrder2[1]->id);

        $order = $orders[1];
        $this->assertEquals(2, $order->id);
        $this->assertTrue($order->isRelationPopulated('itemsInOrder2'));
        $this->assertEquals(3, count($order->itemsInOrder2));
        $this->assertEquals(5, $order->itemsInOrder2[0]->id);
        $this->assertEquals(3, $order->itemsInOrder2[1]->id);
        $this->assertEquals(4, $order->itemsInOrder2[2]->id);

        $order = $orders[2];
        $this->assertEquals(3, $order->id);
        $this->assertTrue($order->isRelationPopulated('itemsInOrder2'));
        $this->assertEquals(1, count($order->itemsInOrder2));
        $this->assertEquals(2, $order->itemsInOrder2[0]->id);
    }

    public function testLink()
    {
Qiang Xue committed
624 625 626 627 628
        /** @var \yii\db\ActiveRecordInterface $orderClass */
        /** @var \yii\db\ActiveRecordInterface $itemClass */
        /** @var \yii\db\ActiveRecordInterface $orderItemClass */
        /** @var \yii\db\ActiveRecordInterface $customerClass */
        $customerClass = $this->getCustomerClass();
629 630
        $orderClass = $this->getOrderClass();
        $orderItemClass = $this->getOrderItemClass();
Qiang Xue committed
631
        $itemClass = $this->getItemClass();
632
        /** @var TestCase|ActiveRecordTestTrait $this */
Alexander Makarov committed
633
        $customer = $customerClass::findOne(2);
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
        $this->assertEquals(2, count($customer->orders));

        // has many
        $order = new $orderClass;
        $order->total = 100;
        $this->assertTrue($order->isNewRecord);
        $customer->link('orders', $order);
        $this->afterSave();
        $this->assertEquals(3, count($customer->orders));
        $this->assertFalse($order->isNewRecord);
        $this->assertEquals(3, count($customer->getOrders()->all()));
        $this->assertEquals(2, $order->customer_id);

        // belongs to
        $order = new $orderClass;
        $order->total = 100;
        $this->assertTrue($order->isNewRecord);
Alexander Makarov committed
651
        $customer = $customerClass::findOne(1);
652 653 654 655 656 657 658
        $this->assertNull($order->customer);
        $order->link('customer', $customer);
        $this->assertFalse($order->isNewRecord);
        $this->assertEquals(1, $order->customer_id);
        $this->assertEquals(1, $order->customer->primaryKey);

        // via model
Alexander Makarov committed
659
        $order = $orderClass::findOne(1);
660 661
        $this->assertEquals(2, count($order->items));
        $this->assertEquals(2, count($order->orderItems));
Alexander Makarov committed
662
        $orderItem = $orderItemClass::findOne(['order_id' => 1, 'item_id' => 3]);
663
        $this->assertNull($orderItem);
Alexander Makarov committed
664
        $item = $itemClass::findOne(3);
665 666 667 668
        $order->link('items', $item, ['quantity' => 10, 'subtotal' => 100]);
        $this->afterSave();
        $this->assertEquals(3, count($order->items));
        $this->assertEquals(3, count($order->orderItems));
Alexander Makarov committed
669
        $orderItem = $orderItemClass::findOne(['order_id' => 1, 'item_id' => 3]);
670 671 672 673 674 675 676
        $this->assertTrue($orderItem instanceof $orderItemClass);
        $this->assertEquals(10, $orderItem->quantity);
        $this->assertEquals(100, $orderItem->subtotal);
    }

    public function testUnlink()
    {
Qiang Xue committed
677 678 679 680 681
        /** @var \yii\db\ActiveRecordInterface $customerClass */
        $customerClass = $this->getCustomerClass();
        /** @var \yii\db\ActiveRecordInterface $orderClass */
        $orderClass = $this->getOrderClass();

682 683
        /** @var TestCase|ActiveRecordTestTrait $this */
        // has many
Alexander Makarov committed
684
        $customer = $customerClass::findOne(2);
685 686 687 688
        $this->assertEquals(2, count($customer->orders));
        $customer->unlink('orders', $customer->orders[1], true);
        $this->afterSave();
        $this->assertEquals(1, count($customer->orders));
Alexander Makarov committed
689
        $this->assertNull($orderClass::findOne(3));
690 691

        // via model
Alexander Makarov committed
692
        $order = $orderClass::findOne(2);
693 694 695 696 697 698 699 700 701 702 703 704 705
        $this->assertEquals(3, count($order->items));
        $this->assertEquals(3, count($order->orderItems));
        $order->unlink('items', $order->items[2], true);
        $this->afterSave();
        $this->assertEquals(2, count($order->items));
        $this->assertEquals(2, count($order->orderItems));
    }

    public static $afterSaveNewRecord;
    public static $afterSaveInsert;

    public function testInsert()
    {
Qiang Xue committed
706
        /** @var \yii\db\ActiveRecordInterface $customerClass */
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
        $customerClass = $this->getCustomerClass();
        /** @var TestCase|ActiveRecordTestTrait $this */
        $customer = new $customerClass;
        $customer->email = 'user4@example.com';
        $customer->name = 'user4';
        $customer->address = 'address4';

        $this->assertNull($customer->id);
        $this->assertTrue($customer->isNewRecord);
        static::$afterSaveNewRecord = null;
        static::$afterSaveInsert = null;

        $customer->save();
        $this->afterSave();

        $this->assertNotNull($customer->id);
723
        $this->assertTrue(static::$afterSaveNewRecord);
724 725 726 727 728 729
        $this->assertTrue(static::$afterSaveInsert);
        $this->assertFalse($customer->isNewRecord);
    }

    public function testUpdate()
    {
Qiang Xue committed
730
        /** @var \yii\db\ActiveRecordInterface $customerClass */
731 732 733
        $customerClass = $this->getCustomerClass();
        /** @var TestCase|ActiveRecordTestTrait $this */
        // save
Alexander Makarov committed
734
        $customer = $customerClass::findOne(2);
735 736 737 738 739 740 741 742 743 744 745 746 747
        $this->assertTrue($customer instanceof $customerClass);
        $this->assertEquals('user2', $customer->name);
        $this->assertFalse($customer->isNewRecord);
        static::$afterSaveNewRecord = null;
        static::$afterSaveInsert = null;

        $customer->name = 'user2x';
        $customer->save();
        $this->afterSave();
        $this->assertEquals('user2x', $customer->name);
        $this->assertFalse($customer->isNewRecord);
        $this->assertFalse(static::$afterSaveNewRecord);
        $this->assertFalse(static::$afterSaveInsert);
Alexander Makarov committed
748
        $customer2 = $customerClass::findOne(2);
749 750 751
        $this->assertEquals('user2x', $customer2->name);

        // updateAll
Alexander Makarov committed
752
        $customer = $customerClass::findOne(3);
753 754 755 756
        $this->assertEquals('user3', $customer->name);
        $ret = $customerClass::updateAll(['name' => 'temp'], ['id' => 3]);
        $this->afterSave();
        $this->assertEquals(1, $ret);
Alexander Makarov committed
757
        $customer = $customerClass::findOne(3);
758 759 760 761 762 763 764 765 766 767 768 769 770
        $this->assertEquals('temp', $customer->name);

        $ret = $customerClass::updateAll(['name' => 'tempX']);
        $this->afterSave();
        $this->assertEquals(3, $ret);

        $ret = $customerClass::updateAll(['name' => 'temp'], ['name' => 'user6']);
        $this->afterSave();
        $this->assertEquals(0, $ret);
    }

    public function testUpdateAttributes()
    {
Qiang Xue committed
771
        /** @var \yii\db\ActiveRecordInterface $customerClass */
772 773 774
        $customerClass = $this->getCustomerClass();
        /** @var TestCase|ActiveRecordTestTrait $this */
        // save
Alexander Makarov committed
775
        $customer = $customerClass::findOne(2);
776 777 778 779 780 781 782 783 784 785 786 787
        $this->assertTrue($customer instanceof $customerClass);
        $this->assertEquals('user2', $customer->name);
        $this->assertFalse($customer->isNewRecord);
        static::$afterSaveNewRecord = null;
        static::$afterSaveInsert = null;

        $customer->updateAttributes(['name' => 'user2x']);
        $this->afterSave();
        $this->assertEquals('user2x', $customer->name);
        $this->assertFalse($customer->isNewRecord);
        $this->assertFalse(static::$afterSaveNewRecord);
        $this->assertFalse(static::$afterSaveInsert);
Alexander Makarov committed
788
        $customer2 = $customerClass::findOne(2);
789 790
        $this->assertEquals('user2x', $customer2->name);

Alexander Makarov committed
791
        $customer = $customerClass::findOne(1);
792 793 794 795 796 797 798
        $this->assertEquals('user1', $customer->name);
        $this->assertEquals(1, $customer->status);
        $customer->name = 'user1x';
        $customer->status = 2;
        $customer->updateAttributes(['name']);
        $this->assertEquals('user1x', $customer->name);
        $this->assertEquals(2, $customer->status);
Alexander Makarov committed
799
        $customer = $customerClass::findOne(1);
800 801 802 803 804 805
        $this->assertEquals('user1x', $customer->name);
        $this->assertEquals(1, $customer->status);
    }

    public function testUpdateCounters()
    {
Qiang Xue committed
806
        /** @var \yii\db\ActiveRecordInterface $orderItemClass */
807 808 809 810
        $orderItemClass = $this->getOrderItemClass();
        /** @var TestCase|ActiveRecordTestTrait $this */
        // updateCounters
        $pk = ['order_id' => 2, 'item_id' => 4];
Alexander Makarov committed
811
        $orderItem = $orderItemClass::findOne($pk);
812 813 814 815 816
        $this->assertEquals(1, $orderItem->quantity);
        $ret = $orderItem->updateCounters(['quantity' => -1]);
        $this->afterSave();
        $this->assertEquals(1, $ret);
        $this->assertEquals(0, $orderItem->quantity);
Alexander Makarov committed
817
        $orderItem = $orderItemClass::findOne($pk);
818 819 820 821
        $this->assertEquals(0, $orderItem->quantity);

        // updateAllCounters
        $pk = ['order_id' => 1, 'item_id' => 2];
Alexander Makarov committed
822
        $orderItem = $orderItemClass::findOne($pk);
823 824 825 826 827 828 829
        $this->assertEquals(2, $orderItem->quantity);
        $ret = $orderItemClass::updateAllCounters([
            'quantity' => 3,
            'subtotal' => -10,
        ], $pk);
        $this->afterSave();
        $this->assertEquals(1, $ret);
Alexander Makarov committed
830
        $orderItem = $orderItemClass::findOne($pk);
831 832 833 834 835 836
        $this->assertEquals(5, $orderItem->quantity);
        $this->assertEquals(30, $orderItem->subtotal);
    }

    public function testDelete()
    {
Qiang Xue committed
837
        /** @var \yii\db\ActiveRecordInterface $customerClass */
838 839 840
        $customerClass = $this->getCustomerClass();
        /** @var TestCase|ActiveRecordTestTrait $this */
        // delete
Alexander Makarov committed
841
        $customer = $customerClass::findOne(2);
842 843 844 845
        $this->assertTrue($customer instanceof $customerClass);
        $this->assertEquals('user2', $customer->name);
        $customer->delete();
        $this->afterSave();
Alexander Makarov committed
846
        $customer = $customerClass::findOne(2);
847 848 849
        $this->assertNull($customer);

        // deleteAll
Qiang Xue committed
850
        $customers = $customerClass::find()->all();
851 852 853 854
        $this->assertEquals(2, count($customers));
        $ret = $customerClass::deleteAll();
        $this->afterSave();
        $this->assertEquals(2, $ret);
Qiang Xue committed
855
        $customers = $customerClass::find()->all();
856 857 858 859 860 861 862 863 864 865 866 867 868
        $this->assertEquals(0, count($customers));

        $ret = $customerClass::deleteAll();
        $this->afterSave();
        $this->assertEquals(0, $ret);
    }

    /**
     * Some PDO implementations(e.g. cubrid) do not support boolean values.
     * Make sure this does not affect AR layer.
     */
    public function testBooleanAttribute()
    {
Qiang Xue committed
869
        /** @var \yii\db\ActiveRecordInterface $customerClass */
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
        $customerClass = $this->getCustomerClass();
        /** @var TestCase|ActiveRecordTestTrait $this */
        $customer = new $customerClass();
        $customer->name = 'boolean customer';
        $customer->email = 'mail@example.com';
        $customer->status = true;
        $customer->save(false);

        $customer->refresh();
        $this->assertEquals(1, $customer->status);

        $customer->status = false;
        $customer->save(false);

        $customer->refresh();
        $this->assertEquals(0, $customer->status);

Qiang Xue committed
887
        $customers = $customerClass::find()->where(['status' => true])->all();
888 889
        $this->assertEquals(2, count($customers));

Qiang Xue committed
890
        $customers = $customerClass::find()->where(['status' => false])->all();
891 892 893 894 895
        $this->assertEquals(1, count($customers));
    }

    public function testAfterFind()
    {
Qiang Xue committed
896
        /** @var \yii\db\ActiveRecordInterface $customerClass */
897 898 899 900 901 902 903 904 905 906 907 908
        $customerClass = $this->getCustomerClass();
        /** @var BaseActiveRecord $orderClass */
        $orderClass = $this->getOrderClass();
        /** @var TestCase|ActiveRecordTestTrait $this */

        $afterFindCalls = [];
        Event::on(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_FIND, function ($event) use (&$afterFindCalls) {
            /** @var BaseActiveRecord $ar */
            $ar = $event->sender;
            $afterFindCalls[] = [get_class($ar), $ar->getIsNewRecord(), $ar->getPrimaryKey(), $ar->isRelationPopulated('orders')];
        });

Alexander Makarov committed
909
        $customer = $customerClass::findOne(1);
910 911 912 913
        $this->assertNotNull($customer);
        $this->assertEquals([[$customerClass, false, 1, false]], $afterFindCalls);
        $afterFindCalls = [];

Qiang Xue committed
914
        $customer = $customerClass::find()->where(['id' => 1])->one();
915 916 917 918
        $this->assertNotNull($customer);
        $this->assertEquals([[$customerClass, false, 1, false]], $afterFindCalls);
        $afterFindCalls = [];

Qiang Xue committed
919
        $customer = $customerClass::find()->where(['id' => 1])->all();
920 921 922 923
        $this->assertNotNull($customer);
        $this->assertEquals([[$customerClass, false, 1, false]], $afterFindCalls);
        $afterFindCalls = [];

Qiang Xue committed
924
        $customer = $customerClass::find()->where(['id' => 1])->with('orders')->all();
925 926 927 928 929 930 931 932
        $this->assertNotNull($customer);
        $this->assertEquals([
            [$this->getOrderClass(), false, 1, false],
            [$customerClass, false, 1, true],
        ], $afterFindCalls);
        $afterFindCalls = [];

        if ($this instanceof \yiiunit\extensions\redis\ActiveRecordTest) { // TODO redis does not support orderBy() yet
Qiang Xue committed
933
            $customer = $customerClass::find()->where(['id' => [1, 2]])->with('orders')->all();
934 935
        } else {
            // orderBy is needed to avoid random test failure
Qiang Xue committed
936
            $customer = $customerClass::find()->where(['id' => [1, 2]])->with('orders')->orderBy('name')->all();
937 938 939 940 941 942 943 944 945 946 947 948 949
        }
        $this->assertNotNull($customer);
        $this->assertEquals([
            [$orderClass, false, 1, false],
            [$orderClass, false, 2, false],
            [$orderClass, false, 3, false],
            [$customerClass, false, 1, true],
            [$customerClass, false, 2, true],
        ], $afterFindCalls);
        $afterFindCalls = [];

        Event::off(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_FIND);
    }
950

951
}