我正在尝试返回一个列表events
,并包括city
它发生的位置。城市仅通过事件关联Venue
。
下面是我正在使用的代码。它返回所有正确的数据,但不返回任何城市数据(除了 Venue 中的 city_id 字段 - 我不确定它为什么返回)。
协会:
Event belongsTo Venue
Venue hasMany Event
Venue belongsTo City
City hasMany Venue
代码:
$this->Event->Behaviors->attach('Containable');
$events = $this->Event->find('all', array(
'limit' => 5,
'order' => 'Event.created DESC',
'fields' => array(
'name',
'description',
'phone',
'price_general',
'price_child',
'price_adult',
'price_child',
'tickets_url'
),
'contain' => array(
'Venue' => array(
'fields' => array(
'name',
'address',
'city_id',
),
'City' => array(
'fields' => array(
'City.name',
'state'
),
'conditions' => array(
'City.id' => 'Venue.city_id'
)
)
),
'Schedule' => array(
'fields'=>array(),
'Date' => array(
'conditions'=>array(
'Date.start >=' => $start_date,
'Date.start <=' => $end_date,
)
)
)
),
));
奖励答案:(我目前在另一个 StackOverflow 问题中问过) - 日期条件应该过滤显示哪些事件,但相反,它们只过滤要显示的日期数据。
工作答案:(感谢bancer)
$this->Event->recursive = -1;
$options['joins'] = array(
array('table' => 'schedules',
'alias' => 'Schedule',
'type' => 'LEFT',
'conditions' => array(
'Event.id = Schedule.event_id',
)
),
array('table' => 'dates',
'alias' => 'Date',
'type' => 'LEFT',
'conditions' => array(
'Date.schedule_id = Schedule.id',
)
)
);
$options['fields'] = array(
'Event.name',
'Schedule.start_date',
'Date.start',
);
$options['limit'] = 5;
$events = $this->Event->find('all', $options);