2013-10-24 55 views
3

這段代碼爲什麼被破壞?這應該工作,但它不。爲什麼這個PHP activerecord關聯不起作用?

我有三個表:

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' 
+2

你可能需要在你的'Subject'模型'靜態$ belongs_to'。請參閱文檔:http://www.phpactiverecord.org/projects/main/wiki/Associations#has_many_through –

回答

1

看起來像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') 
); 
} 
+0

爲了強調,應爲兩個模型定義'$ has_many'。你不能只在'Application'上定義它。如果你只在'Application'上定義它,那麼你每次都必須使用'include'選項來加載'subjects'。在兩者上定義它,都可以在不預先加載它們的情況下引用'$ app-> subjects'。 –