2011-09-23 156 views
1

没问题,只是一个关于良好的代码写作的问题。我仍然在学习Symfony + ORM,并且在这些框架中没有定位。关系主义查询和访问

我在我的数据库表中的用户(与登录栏)和帐户(也与登录栏,这是不同于登录用户)。

一个用户(由ID识别为数据库和由登录为登录)有许多帐户(也鉴定ID和登录其用作帐户名称)。因此,在schema.yml中关系是:

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

现在我想访问所有以下列方式(比方说我只显示当前的帐户登录的名单与一个用户登录账号的登录用户现在):

 /* $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 />"; 
     } 

此代码工作得很好。然而,我现在想知道的是,如果这不是丑陋或不是实现这一目标的最佳方式?就像我说的,我在Symfony中没有太多的定位,并且不知道哪些编程方法是推荐的,哪些不是。

回答

0

这看起来不那么对我不好,但我已经写这样的:

/* $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 />"; 
}