Search code examples
phpcodeigniterormphpactiverecord

PHP ActiveRecord - Could not find the association in model


I'm using Codeigniter 2.1.0 along with the spark to enable PHP ActiveRecord and I am unable to create a many to many association through a lookup table. Whenever I load the Event model it fails with "Could not find the association eventcategories in model Event" which is a ActiveRecord\HasManyThroughAssociationException

In accordance to this topic I've tried updating my source with this patch with no effect.

I also followed this thread and based my association on the solution given there.

I've ended up with the following sql: http://pastebin.com/ya65VWHC and the following models: http://pastebin.com/XEDTb6KS

I'm trying to associate one Event with several categories, for example a football game event could have the categories 'sports', 'family' and 'fun'.

Did I miss something fundamental?


Solution

  • I'm not able to test everything as I don't have a database I could dump your code into (and don't have any test data either :) ), but your code has some differences with the manual.

    If you look at this page: http://www.phpactiverecord.org/projects/main/wiki/Associations#has_many_through

    You see three tables, that map like this ( I think )

     Order        -> Category   
     Payment      -> Eventcategory 
     User         -> Event
    

    A Category has multiple Events through Eventcategory, just like an Order has several Users through Payment in the example. The other way around is defined more basic (a User has Orders)

    Where you have defined 2 "through" relationships, this example only has one in the Order class, leaving the user with just a has_many. That's a big difference I think you might need to address.

    Also, I'm not really sure about the foreign_key definitions you do in this part:

    array('events', 'foreign_key' => 'event_id',
                  array('through' => 'eventcategories', 'foreign_key' => 'event_id')
    

    Iif you've got the default naming scheme you don't need to bother with explicitly naming them.

    To fix it, I would start with the order/user/payment example, check that it works for you, and then replace all the parts (carefully :) ) so it becomes your code.