3

为什么这段代码被破坏了?这应该工作,但它没有。

我有三张桌子:

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

这些是我的模型:

<? # 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")
    );
  }
?>

这是我访问模型的代码:

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

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

然而,当我运行代码时,我得到:

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

1 回答 1

2

看起来像是ApplicationSubject一个连接模型。

如果是这样,请考虑以下设置...

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')
  );
}
于 2014-04-23T22:10:11.343 回答