Tronic Tronic
Tronic Tronic

Reputation: 13

get Id for other table in Symfony

table: USERS
| id | name | city_id |
| 1  | jonh |  1      |
table: CITY
| id | city_ name |
| 1  | London |

in action.class:

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

and this generate:

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


| 1 | john | 1 |

how can i make:

| 1 | jonh | London |

?

i make in 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();

and in action.class:

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

then i have error:

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

Upvotes: 1

Views: 1679

Answers (2)

Inoryy
Inoryy

Reputation: 8425

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

instead of

return $q->fetchOne();

Upvotes: 0

Grad van Horck
Grad van Horck

Reputation: 4506

The reason you get the error is because you are calling getCityId() on the collection class: the query you execute (SELECT * FROM users....) returns multiple users, so it is a collection. You have to loop through the results to get the invidual results. If you expect a query to return only one result you can use fetchOne() instead of execute() on your query.

You can reference related records just by their relation name.

$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();
}

Upvotes: 1

Related Questions