Create and get from a Model
public static fromModel ( Phalcon\Mvc\ModelInterface $subject ) : Phalcon\Mvc\ModelInterface | ||
$subject | Phalcon\Mvc\ModelInterface | |
return | Phalcon\Mvc\ModelInterface |
public function testBelongsTo() { $rawly = Bug::findFirstById(1); $rawly->robot; $eagerly = Loader::fromModel(Bug::findFirstById(1), 'Robot'); $this->assertTrue(property_exists($eagerly, 'robot')); $this->assertInstanceOf('Phalcon\\Test\\Mvc\\Model\\EagerLoading\\Stubs\\Robot', $eagerly->robot); $this->assertEquals($rawly->robot->readAttribute('id'), $eagerly->robot->readAttribute('id')); // Reverse $rawly = Robot::findFirstById(2); $rawly->bugs = $this->resultSetToEagerLoadingEquivalent($rawly->bugs); $eagerly = Loader::fromModel(Robot::findFirstById(2), 'Bugs'); $this->assertTrue(property_exists($eagerly, 'bugs')); $this->assertContainsOnlyInstancesOf('Phalcon\\Test\\Mvc\\Model\\EagerLoading\\Stubs\\Bug', $eagerly->bugs); $getIds = function ($obj) { return $obj->readAttribute('id'); }; $this->assertEquals(array_map($getIds, $rawly->bugs), array_map($getIds, $eagerly->bugs)); $this->assertEmpty(Loader::fromModel(Robot::findFirstById(1), 'Bugs')->bugs); // Test from multiple $rawly = $this->resultSetToEagerLoadingEquivalent(Bug::find(['limit' => 10])); foreach ($rawly as $bug) { $bug->robot; } $eagerly = Loader::fromResultset(Bug::find(array('limit' => 10)), 'Robot'); $this->assertTrue(is_array($eagerly)); $this->assertTrue(array_reduce($eagerly, function ($res, $bug) { return $res && property_exists($bug, 'robot'); }, true)); $getIds = function ($obj) { return property_exists($obj, 'robot') && isset($obj->robot) ? $obj->robot->readAttribute('id') : null; }; $this->assertEquals(array_map($getIds, $rawly), array_map($getIds, $eagerly)); }
public function testHasManyToMany() { $rawly = Robot::findFirstById(1); $rawly->parts; $eagerly = Loader::fromModel(Robot::findFirstById(1), 'Parts'); $this->assertTrue(property_exists($eagerly, 'parts')); $this->assertTrue(is_array($eagerly->parts)); $this->assertSame(count($eagerly->parts), $rawly->parts->count()); $getIds = function ($arr) { $ret = array(); foreach ($arr as $r) { if (is_object($r)) { $ret[] = $r->readAttribute('id'); } } return $ret; }; $this->assertEquals($getIds($this->resultSetToEagerLoadingEquivalent($rawly->parts)), $getIds($eagerly->parts)); }