Bruno Cassol Mon Sep 24 09:15:25 -0400 2012

Subject: Problem in many-many association

person
_____________
- id
- name
phone_number
_____________
- id
- number
person_has_phone_number
_____________
- person_id
- phone_number_id
1 /* models/Person.php */
2 class Person extends BaseModel {
3     static $table_name = 'person';
4     static $has_many = array(
5         array('person_has_phone_number'),
6         array('phone_numbers', 'through' => 'person_has_phone_number')
7     );
8 }
1 /* models/PhoneNumber.php */
2 class PhoneNumber extends BaseModel {
3     static $table_name = 'phone_number';
4     static $has_many = array(
5         array('person_has_phone_number')
6     );
7 }
1 /* models/PersonHasPhoneNumber.php */
2 class PersonHasPhoneNumber extends BaseModel {
3     static $table_name = 'person_has_phone_number';
4     static $belongs_to = array(
5         array('person'),
6         array('phone_number')
7     );
8 }

I manually inserted 2 phone numbers, 1 person and associated them in person_has_phone_number table.

Why this only returns one phone number?

1 $person = Person::find('first', array('include' => array('phone_numbers')));
2 var_dump($person->to_json(array('include' => array('phone_numbers'))));

I expected 2 phone numbers but I only got one:

string '{"id":1,"name":"Bruno Cassol","phone_numbers":
[{"id":1,"description":"Celular","number":"12345678"}]}' (length=101)

After turning logging on I saw the SQL being executed is:

SELECT `phone_number`.* 
FROM `phone_number` 
INNER JOIN `person_has_phone_number` 
ON(`phone_number`.id = `person_has_phone_number`.phone_number_id) 
WHERE `person_id` IN(1)

Executing this same SQL in phpMyAdmin returns 2 records. But phpActiveRecord only shows me 1. =(