2011-09-23 57 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 />"; 
}