2011-06-28 21 views
1
table: USERS 
| id | name | city_id | 
| 1 | jonh | 1  | 
table: CITY 
| id | city_ name | 
| 1 | London | 
在action.class

獲得ID爲其他表:在Symfony的

$this->user_list = Doctrine::getTable('Users') 
     ->createQuery('a') 
     ->execute(); 

,這產生:

$user_lists->getId(); 
$user_lists->getName(); 
$user_lists->getCityId(); 


| 1 | john | 1 | 

我怎樣才能讓:

| 1 | jonh | London | 

我做出UsersTableClass:

public function getCityName($id) { 

     $q = $this->createQuery('j') 
     ->select('u.name, c.city_name') 
     ->from('Users u') 
     ->where('city_id = ?', $id) 
     ->leftJoin('u.city c'); 

     return $q->fetchOne(); 
} 


$user_lists->getId(); 
$city_name; 
$user_lists->getCityId(); 

和action.class:

$this->user_list = Doctrine::getTable('Users') 
     ->createQuery('a') 
     ->execute(); 
$this->city_name = Doctrine::getTable('Users')->getCityName($this->user_list->getCityId()); 

然後我有錯誤:

Fatal error: Call to undefined method Doctrine_Collection::getCityId()

回答

1

你原因的錯誤是因爲你在集合類中調用getCityId():您執行的查詢(SELECT * FROM users....)r影響多個用戶,所以它是一個集合。您必須循環查看結果才能得到結果。如果您希望某個查詢只返回一個結果,則可以在查詢中使用fetchOne()而不是​​。

只能通過關係名稱引用相關記錄。的

$this->user_list = Doctrine::getTable('Users') 
     ->createQuery('u') 
     ->leftJoin('u.City'); // <-- Added for performance 
     ->execute(); 

foreach($this->user_list as $user) { 
    $id = $user->id;    // is the same as $user->getId() 
    $name = $user->name;   // == $user->getName(); 
    $cityName = $user->City->name; // == $user->getCity()->getName(); 
} 
+0

的感謝!這很好! –

0
return $q->execute()->getFirst(); 

代替

return $q->fetchOne();