jonathangeiger / kohana-jelly

See the link below for the most up-to-date code
https://github.com/creatoro/jelly
MIT License
146 stars 34 forks source link

Self referencing model (hasmany and belongsto itself) #150

Open SpadXIII opened 14 years ago

SpadXIII commented 14 years ago

I just upgraded to the master branch (0.9.6.2-14 coming from 0.9.6.2-0) and my self-referencing model stopped working.

model:

$meta->table('categories')
    ->sorting(array('LENGTH("name")' => 'ASC', 'name' => 'ASC'))
    ->fields(array(
        'id' => new Field_Primary,
        'categories' => new Field_HasMany(array(
            'label' => __('Categories'),
        )),
        'category' => new Field_BelongsTo(array(
            'label' => __('Category'),
            'null' => TRUE,
        )),
        'status' => new Field_Status,
        'name' => new Field_String,
    ));

When trying to fetch the sub-categories ($model->categories) it fails with a wrong query:

SELECT `categories`.`id` AS `id`, `categories`.`category_id` AS `category`, `categories`.`name` AS `name` FROM `categories` WHERE `_category:category`.`category_id` = 1 ORDER BY LENGTH(`categories`.`name`) ASC, `categories`.`name` ASC

I've been tracking it down and came around line 709 of Jelly_Builder_Core. This is where it fetches the join_table_alias: _category:category But since the query is not a join, there is no need for the table alias. I've temporarily 'fixed' this addition of _category by first checking for the same model

if ($field_object->model !== $model)
{
    // The model specified looks like a relationship alias in this context
    // that means we alias the field name to a column but use the join alias for the table
    $join_table_alias = Jelly::join_alias($field_object);
}

This seems to work here, as this model also has foreign relations (stripped from above model) which keep working with this 'fix'. Note: I have not tested these foreign relations without this fix.