avenirer / CodeIgniter-MY_Model

Base model (MY_Model) for the Codeigniter framework.
324 stars 203 forks source link

Many-to-many with same table? #275

Open wallyholt opened 6 years ago

wallyholt commented 6 years ago

Is it possible to set up a 'has-many-pivot' relationship where the pivot table is mapping a relationship between records in the same table.

In my case, I have a location_model on top of table 'locations' and tried to define the following relationship in my location_model: $this->has_many_pivot['related'] = array( 'foreign_model'=>'location_model', 'pivot_table'=>'related_locations', 'local_key'=>'id', 'pivot_local_key'=>'location_id', 'pivot_foreign_key'=>'related_location_id', 'foreign_key'=>'id' );

A call to $record = $this->location_mode->with_related()->get(1); results in the following SQL that fails with SQL Error 1066: Not unique table/alias: 'locations'

SELECT locations.id, related_locations.location_id FROM locations LEFT JOIN related_locations ON locations.id = related_locations.related_location_id LEFT JOIN locations ON related_locations.location_id = locations.id WHERE related_locations.location_id IN('1')

Is there currently a way to have MY_Model alias one (or both) of the tables?