我正试图从表之间的关系中获取属性,但它似乎无法正常工作,我在网上尝试了其他解决方案,但仍然无法正常工作,这里的代码如下:
$data = Employer::with(['contratClient'=>function($query){$query->select("idcontrat");}])
->where("id_entre",1)
->get();
echo "<pre>";
dd($data[0]->contratClient);
echo "</pre>";
雇主模型:
class Employer extends Model{
protected $primaryKey = 'id_em';
protected $table = 'employers';
protected $guarded = array();
public function contratClient(){
return $this->hasMany("App\ContratClient","id_emp");
}
}
ContratClient模型:
class ContratClient extends Model
{
protected $primaryKey = 'idcontrat';
protected $table = 'contratClients';
public function employer(){
return $this->belongsTo('App\Employer','id_em');
}
}
这是结果:
如果我想念任何东西请我上市,仍然是Laravel的初学者
谢谢
模型关系应该是:
class Employer extends Model{
protected $primaryKey = 'id_em';
protected $table = 'employers';
protected $guarded = array();
public function contratClient(){
return $this->hasMany("App\ContratClient","id_emp", "id_em");
}
}
class ContratClient extends Model
{
protected $primaryKey = 'idcontrat';
protected $table = 'contratClients';
public function employer(){
return $this->belongsTo('App\Employer','id_emp', 'id_em');
}
}
要验证关系,请先尝试获取以下行:
$data = Employer::with('contratClient')->get();
我认为你的主要关键不是laravel所要求的。例如 :
在employers
表中,laravel需要employer_id
,但你的主键是id_em
。请将您的关系更新为以下内容并再次检查:
class Employer extends Model{
protected $primaryKey = 'id_em';
protected $table = 'employers';
protected $guarded = array();
public function contratClient(){
return $this->hasMany('App\ContratClient','foreign_key_in_this_table', 'idcontrat');
}
}
class ContratClient extends Model
{
protected $primaryKey = 'idcontrat';
protected $table = 'contratClients';
public function employer(){
return $this->belongsTo('App\Employer','foreign_key_in_this_table', 'id_em');
}
}
还只是检查它是否是类型contratClients
,你的意思是contractClients
?