从Doctrine中的两个表中检索数据

时间:2012-10-08 14:21:21

标签: php doctrine symfony-1.4

我在这里遇到了一个问题:

$advList = Doctrine::getTable('Advertiser')
        ->createQuery('a')
        ->leftJoin('a.PrincCity p')
        ->leftJoin('a.TourCity t')
        ->leftJoin('a.Category')
        ->orderBy('a.new DESC')
        ->where('a.is_activated = ?', true)
        ->andWhereNotIn('a.category_id', array(4, 5))
        ->andWhere('( (t.slug IS NULL AND p.slug = ?) OR t.slug = ?)', array($city_slug, $city_slug))
        ->addOrderBy('a.created_at DESC');

    $this->pager = new sfDoctrinePager('Advertiser', 50);
    $this->pager->setQuery($advList);
    $this->pager->setPage($request->getParameter('page', 1));
    $this->pager->init();

此代码从一个城市获取所有广告客户(由表广告客户中的ID表示) - 现在我有第二个表广告客户城市包含id,AdvertiserId和CityID所以我可以为一个广告客户拥有多个城市(例如,5个广告客户ID 99和不同的CityID)。

问题在于我需要从一个城市获得所有广告客户,但是高级代码只能使用数据库中的一个表,因此我不知道如何在第二个中搜索(使用其他城市)。 / p>

1 个答案:

答案 0 :(得分:1)

我不确定我是否能理解您的问题,但我认为如果您明确定义了n-m广告客户 - 城市关系:

Advertiser:
  ...
  relations:
    Cities: { class: City, refClass: AdvertiserCity, local: advertiser_id, foreign: city_id } 

AdvertiserCity:
  columns:
    advertiser_id: { type: integer,...}
    city_id: { type: integer,....}
  ...
  relations:
    City: { local: city_id, foreign: id, foreignAlias: AdvertiserCities } 
    Advertiser: { local: advertiser_id, foreign: id, foreignAlias: AdvertiserCities } 

然后,您的查询可以像:

$advList = Doctrine::getTable('Advertiser')
        ->createQuery('a')
        ->innerJoin('a.Cities c')
        ...
        ->addWhere('c.id = ?',$city_id)
        ...;