2014-03-01 79 views
0

我试图将多个模型绑定到一个窗体。目前,我有4种型号:通过另一个模型Laravel 4模型关系

<?php 

class DemDataSet extends Eloquent { 

    public $timestamps = false; 
    protected $connection = 'epcr_dem_data'; 
    protected $table = 'DEMDataSet'; 
    protected $primaryKey = 'pk_DEMDataSet'; 

    public function DemographicReport(){ 
     return $this->hasOne('DemographicReport','fk_DemDataSet','pk_DemDataSet'); 
    } 

} 

class DemographicReport extends Eloquent { 

    public $timestamps = false; 
    protected $connection = 'epcr_dem_data'; 
    protected $table = 'DemographicReport'; 
    protected $primaryKey = 'pk_DemographicReport'; 

    public function DemDataSet(){ 
     return $this->belongsTo('DemDataSet','fk_DemDataSet','pk_DemDataSet'); 
    } 

    public function dAgency(){ 
     return $this->hasOne('dAgency','fk_DemographicReport','pk_DemographicReport'); 
    } 

} 

class dAgency extends Eloquent { 

    public $timestamps = false; 
    protected $connection = 'epcr_dem_data'; 
    protected $table = 'dAgency'; 
    protected $primaryKey = 'pk_dAgency'; 

    public function DemographicReport(){ 
     return $this->belongsTo('DemographicReport','fk_DemographicReport','pk_DemographicReport'); 
    } 

    public function dAgency_10(){ 
     return $this->hasMany('dAgency_10','fk_dAgency','pk_dAgency'); 
    } 

} 

class dAgency_10 extends Eloquent { 

    public $timestamps = false; 
    protected $connection = 'epcr_dem_data'; 
    protected $table = 'dAgency_10'; 
    protected $primaryKey = 'pk_dAgency_10'; 

    public function dAgency(){ 
     return $this->belongsTo('dAgency','fk_dAgency','pk_dAgency'); 
    } 

} 

?> 

而且我将它传递给我的看法通过我的控制器,就像这样:

public function index() 
{ 
    //THIS is the line I need help with (I think): 
    $agency = dAgency::with('dAgency_10','DemographicReport')->find(1); 

    //for troubleshooting: 
    echo "<pre>",print_r(dAgency::with('dAgency_10','DemographicReport')->find(1)->toArray()),"</pre>"; 

    return View::make('test') 
     ->with('agency', $agency); 
} 

我能够绑定一切除了从DemDataSet模型数据,我甚至无法弄清楚如何建立它与我的模型之间的关系。所以基本上,我只想让DemviewSet模型中的字段可用于我的视图,然后显然我希望能够最终执行所有CRUD操作。

回答

0

看着你的模型,你应该能够通过DemographicReport访问它。

$dataset = $agency->DemographicReport->DemDataSet; 
+0

还不行。当我在我的控制器中调用'echo'

",print_r($agency->DemographicReport),"
“;'时,我得到'[relations:protected] => Array([DemDataSet] =>)'表示DemDataSet为空。但是当我查看该模型的结果时('echo“
",print_r(DemDataSet::find(1)),"
”;'),它显然有数据。我仔细检查了我的hasOne()和belongsTo()他们看起来是否正确。 – jreed121

+0

'$ agency-> DemographicReport'是否具有'fk_DemDataSet'的值? – duellsy

+0

是的,它的确如此。我的模特关系显然存在问题。我有一个类似的问题,这可能是同样的问题在这里:http://stackoverflow.com/questions/22165781/laravel-4-deleting-multiple-models-related-by-foreign-keys。在我真正考虑过这个问题的可能性之前,我做了这件事。谢谢你看看男人,我一直在殴打自己,我知道这可能很简单。 – jreed121