2016-10-25 59 views
0

我沒有使用主/外鍵命名約定。我已經建立了模型之間的關係,但是我收到了這條消息。 => Illuminate\Database\Eloquent\Relations\BelongsTo {#617}laravel 5.3使用非默認鍵的關係模型

以下是我的關係:國籍有許多親緣關係。

金德福德型號

<?php 

namespace App\Models; 

use Illuminate\Database\Eloquent\Model; 

class Kindred extends Model 
{ 
//kindreds 
protected $primaryKey = "id_kindred"; 

protected $table = "kindreds"; 

protected $fillable =  ['id_kindred','nombre_kindred','gender_kindred','bd_kindred','works_kindred','company_kindred','notes_kindred','id_natio_fk','id_mar_sta_fk','id_aller_fk','id_treat_fk','id_educa_fk','id_relat_fk','id_type_kindr_fk','id_fam_gro_fk','id_natio_fk','id_mar_sta_fk','id_aller_fk','id_treat_fk','id_educa_fk','id_relat_fk','id_type_kindr_fk','id_fam_gro_fk']; 

public function Nationality() 
{ 
    return $this->belongsTo('App\Models\Nationality', 'id_natio_fk'); 
} 

public function Marital_status() 
{ 
    return $this->belongsTo('App\Models\Matrital_status' , 'id_mar_sta'); 
} 

國籍型號

<?php 

namespace App\Models; 

use Illuminate\Database\Eloquent\Model; 

class Nationality extends Model 
{ 
protected $primaryKey ="id_natio"; 
protected $table = "nationalities"; 

protected $fillable = ['nombre_natio']; 

public function kindreds() 
{ 
    return $this->hasMany('app\Models\Kindred' , 'id_natio_fk'); 
} 

這是我補鍋匠命令行上執行代碼。

>>> $k = App\Models\Kindred::find(111111111); 
=> App\Models\Kindred {#636 
id_kindred: "111111111", 
nombre_kindred: "First Last", 
gender_kindred: "3", 
bd_kindred: "0000-00-00", 
works_kindred: 1, 
company_kindred: "Company", 
notes_kindred: "", 
id_natio_fk: 1, 
id_mar_sta_fk: 1, 
id_aller_fk: 1, 
id_treat_fk: 1, 
id_educa_fk: 1, 
id_relat_fk: 1, 
id_type_kindr_fk: 1, 
id_fam_gro_fk: 1, 
created_at: "2016-10-24 04:21:07", 
updated_at: "2016-10-24 04:21:07", 
} 
>>> $k->Nationality() 
    => Illuminate\Database\Eloquent\Relations\BelongsTo {#617} 

回答

1

您還需要通過傳遞額外的參數給hasManybelongsTo方法來替代本地密鑰。默認情況下,它假定爲id,在您的案例中是id_kindredid_nation

return $this->hasMany('App\Model', 'foreign_key', 'local_key'); 

所以, 金德福德型號:

public function Nationality() 
{ 
    return $this->belongsTo('App\Models\Nationality', 'id_natio_fk', 'id_kindred'); 
} 

國籍型號:

public function kindreds() 
{ 
    return $this->hasMany('app\Models\Kindred' , 'id_natio_fk','id_nation'); 
} 
+0

嗨Sanzeeb,我應用了你的建議,但它不工作,我收到一條錯誤消息,說id_kindred列在國籍表上不存在。 (這是很好),所以我試了這個,它完美地工作Kindred模型:公共職能國籍(){返回$ this-> belongsTo('應用程序\模型\國籍','id_natio_fk','id_natio'); }國籍模型public function Kindreds(){return $ this-> hasMany('app \ Models \ Kindred','id_natio_fk','id_natio'); }如果你看看我添加了id_natio而不是id_kindred,有什麼想法? –

+0

@AndréDeLaOCampos好了,第三個參數是父表的本地鍵。我想到'id_kindred',我很高興你解決了它。 –

0

你想顯示的關係。試試這個

$k->Nationality; // without the '()' 

它應該顯示國籍或空。

+0

感謝您檢查問題,我遵循@Sanzeeb建議,也是您的,最後經過一些額外的修復後,它工作得很好。 –