2016-10-25 121 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建议,也是您的,最后经过一些额外的修复后,它工作得很好。 –