Laravel RelationShip选择字段不起作用

时间:2019-02-19 16:03:57

标签: php laravel eloquent laravel-query-builder

我正在尝试从表之间的关系中获取属性,但它似乎不起作用,我尝试了网络中的其他解决方案,但仍然不起作用,这是我调用的以下代码:

$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');
     }
}

结果如下:

enter image description here

如果我想念任何东西,请列出,仍然是Laravel的初学者

谢谢

2 个答案:

答案 0 :(得分:0)

我认为您的主键不是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吗?

答案 1 :(得分:0)

模型关系应为:

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();
相关问题