开发者

Doctrine querying and accessing with relations

No problem, just a question about good code-writing. I'm still learning Symfony + ORM and have no orientation in these frameworks.

I have in my databa开发者_运维知识库se table User (with login column) and Account (also with login column, which is different than the login in User).

One User (identified by ID for database and by login for logging in) have many Accounts (identified also by ID and login which acts as account-name). So relation in schema.yml is:

Account:
(...)
relations:
  idUser:
    class: User
    local: id_user
    foreign: id_user
    foreignAlias: Accounts

Now I'm trying to access all the Account's logins related to one User's login in the following way (let's say I'm only displaying list of Account's logins of the current user for now):

        /* $u = login-name of the current user */
        $q = Doctrine::getTable('User')->
                createQuery('u')->innerjoin('u.Accounts a WITH u.login=?', $u)->execute();
        foreach($q[0]->Accounts as $v) {
            echo $v->login . "<br />";
        }

This code works very well. However what I wonder now is if isn't it ugly or not the best way to achieve this? Like I said, I have no much orienatation in Symfony and don't know which programming methods are recommended, and which aren't.


This does not look so bad to me, but I'd have written it like this:

/* $login = login-name of the current user */
/* Always use ModelTable::getInstance() instead of Doctrine::getTable : 
   your IDE will give you better auto-completion if the doc block of the
   getInstance has a correct @return annotation.
   You will have all the methods of ModelTable in your auto-completion */
$users = UserTable::getInstance() 
  ->createQuery('u')
    ->innerjoin('u.Accounts a WITH u.login = ?', $login) 
      ->execute(); //Try to align opening parenthesis when writing DQL, it is easier to read

foreach ($users[0]->Accounts as $v) // egyptian brackets are for java(script) programmers
{
  echo $v->login . "<br />";
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜