Padraig
Padraig

Reputation: 3737

Why does this PHP activerecord association not work?

Why is this code broken? This should work but it doesn't.

I have three tables :

applications
   id, name
subjects
   id, name
application_subjects
   application_id, subject_id, notes

These are my models :

<? # Application.php
 class Application extends ActiveRecord\Model
 {
  static $has_many = array(
     array('application_subjects'),
     array('subjects', 'through' => 'application_subjects')
  );
 }
?>

<? # Subject.php
 class Subject extends ActiveRecord\Model
 {
 }
?>

<? # ApplicationSubject.php
  class ApplicationSubject extends ActiveRecord\Model
  {
    static $has_many = array(
       array("subjects")
    );
  }
?>

Here is my code to access the model :

$app = Application::find_by_id(1); # this brings up a valid application record

foreach($app->subjects as $s) {
   echo $s->name;
}

Yet when I run the code I get :

Fatal error: Uncaught exception 'ActiveRecord\HasManyThroughAssociationException' with message 
'Could not find the association application_subjects in model Application'

Upvotes: 3

Views: 832

Answers (1)

Igbanam
Igbanam

Reputation: 6082

Looks like ApplicationSubject is a join model.

If so, consider the following setup...

class Application extends ActiveRecord\Model
{
  static $has_many = array(
    array('application_subjects'),
    array('subjects', 'through' => 'application_subjects')
  );
}

class Subject extends ActiveRecord\Model
{
  static $has_many = array(
    array('application_subjects'),
    array('applications', 'through'=> 'application_subjects')
  );
}

class ApplicationSubject extends ActiveRecord\Model
{
  static $belongs_to = array(
    array('application'),
    array('subject')
  );
}

Upvotes: 2

Related Questions