简体   繁体   中英

Retrieving data from two tables in Doctrine

I got a little problem here:

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

This code gets all advertisers from a city (represented by ID in table Advertiser) - now I have second table Advertiser-City wich contains id, AdvertiserId and CityID so I can have multiple cities for one advertiser (eg 5 rows with AdvertiserID 99 and different CityID).

The problem is that I need to get all advertisers from a city, but upper code can only work with one table in the DB so I don't know how to search in the second one (with the additional cities).

I'm not sure that I can understand your problem, but I think that if you have the nm Advertiser-city relation well defined:

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 } 

Then, your query can go like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM