Bug Report #1289

ORM has_many, belongs_to table aliasing screwed.

Added by thepixeldeveloper - almost 3 years ago. Updated almost 3 years ago.

Status:Closed Start date:
Priority:Urgent Due date:
Assignee:John Heathco % Done:

100%

Category:Libraries:ORM
Target version:2.3.3
Resolution:invalid Points:

Description

In the trunk, the aliasing functionality for the has_many, belongs_to is broken. View the example below.

class News_Model extends ORM
{
    protected $belongs_to = array('category' => 'news_category');
}
class News_category_Model extends ORM_MPTT
{
    protected $has_many = array('articles' => 'news');

}

and in my controller.

public function orm_test()
{
    $news = ORM::factory('news', 10)->find();
    print $news->category->name; // Broken    
    print $news->news_category->name; // This one works.
}

The error displayed using the $news->category->name

Undefined index:  news_id

History

Updated by John Heathco almost 3 years ago

Please provide your database structure any your models.

Updated by Márton Szász almost 3 years ago

In the mean time you could use the foreign key "hack", it sort of works for me:

class thread_Model extends ORM {

    protected $belongs_to = array('author'=>'user');
    protected $load_with = array('author');
    protected $foreign_key = array('author'=>'author');

}

Updated by Mathew Davies almost 3 years ago

Posted some additional information which may help.

Updated by Kiall Mac Innes almost 3 years ago

This looks to caused by the ORM::foreign_key(); method.

$news = ORM::factory('news')->find();
echo $news->foreign_key('category'); // Echos "news_id" 

This is caused by L1122
Tested with latest trunk and this model:

class News_Model extends ORM
{
    protected $belongs_to = array('category' => 'news_category');
}

Updated by John Heathco almost 3 years ago

  • Status changed from New to Closed
  • Resolution set to invalid

Not a bug. When using an alias, it will use the alias name for the foreign key. In this case, it is going to look in the news table for 'category_id' instead of 'news_category_id'. The solutions are to stop using the alias, keep the alias and change the column name to 'category_id', or use the $foreign_key as suggested.

Updated by Mathew Davies almost 3 years ago

Thanks John, this had me puzzled for quite some time. Glad to get it sorted. :)

Updated by Kiall Mac Innes almost 3 years ago

  • % Done changed from 0 to 100

Cant believe I didnt notice it was news_category_id instead of category_id in the table... DOH.

Also available in: Atom PDF