为什么这个 PHP 活动记录关联不起作用


Why does this PHP activerecord association not work?

为什么这段代码坏了?这应该有效,但事实并非如此。

我有三个表:

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'

看起来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')
  );
}