我沒有使用主/外鍵命名約定。我已經建立了模型之間的關係,但是我收到了這條消息。 => 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}
嗨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,有什麼想法? –
@AndréDeLaOCampos好了,第三個參數是父表的本地鍵。我想到'id_kindred',我很高興你解決了它。 –