开发者

retrieving object information with Doctrine

开发者 https://www.devze.com 2022-12-27 11:55 出处:网络
i want to fetch information from the database using objects. i really like this approach cause this is more OOP:

i want to fetch information from the database using objects.

i really like this approach cause this is more OOP:

$user = Doctrine_Core::getTable('User')->find(1);
echo $user->Email['address'];
echo $user->Phonenumbers[0]->phonenumber;

rather than:

$q = Doctrine_Query::create()
    ->from('User u')
    ->leftJoin('u.Email e')
    ->leftJoin('u.Phonenumbers p')
    ->where('u.id = ?', 1);
$user = $q->fetchOne();
echo $user->Email['address'];
echo $user->Phonenumbers[0]['phonenumber'];

the problem is that the first one uses 3 queries (3 different tables), while the second one uses only 1 (and is therefore recommended technique).

but i feel that it destroys the object oriented design. cause ORM is meant to give us an OOP approach so that we could focus on objects and not the relational database. but now they want us to go back to use SQL like pattern.

there isn't a way to get information form multiple tables not usin开发者_Go百科g DQL?

the above examples are taken from the documentation: doctrine


  1. Create a custom method in your Table class that will return proper data:

    class UserTable extends Doctrine_Table {
        public function retrieveOne($id) {
            return $this->createQuery('u')
                        ->leftJoin('u.Email')
                        ->leftJouin('u.Phonenumbers p')
                        ->where('u.id = ?', $id)
                        ->fetchOne();
        }
    }
    
  2. Your final code:

    $user = Doctrine::getTable('User')->retrieveOne(1);
    echo $user['Phonenumbers'][0]['phonenumber'];
    
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号