雄辩的ORM关系在laravel中始终返回null

时间:2018-11-22 04:02:27

标签: laravel laravel-5 eloquent

我有3种型号:

MonHoc模型:

class MonHoc extends Model{
   protected $table='monhoc' ;
   protected $fillable = [
      'mamh', 'phuongthucgiangday', 'tenmh','tinchitichluy','tinchihocphi','hockydenghi',
   ];

   public function monTienQuyet(){
      return $this->hasMany('App\MonTQ','montq_id','id');
   }

   public function monTuyChon(){
      return $this->hasMany('App\MonTC','montc_id','id');
   }
}

MonTC模型:

class MonTC extends Model{
   protected $table='monhoc_tuychon' ;
   protected $fillable = [
      'monhoc_id', 'montc_id',
   ];
   public function monhoc(){
      return $this->belongsTo('App\MonHoc','monhoc_id');
   }
}

MonTQ模型:

class MonTQ extends Model{
   protected $table='montienquyet' ;
   protected $fillable = [
      'monhoc_id', 'montq_id',
   ];    
   public function monhoc(){
      return $this->belongsTo('App\MonHoc','monhoc_id');
   }
}

但是当我在控制器中使用MonHoc模型时:

public function test(MonHoc $monhoc){
   $mon=$monhoc->monTienQuyet->toSql();
   dd($mon);
}

它显示SQL

select * from `montienquyet` where `montienquyet`.`montq_id` is null and `montienquyet`.`montq_id` is not null

它在MySQL中显示为null,因为where子句相反。我不知道为什么模型会导出此SQL!

请帮助!

2 个答案:

答案 0 :(得分:0)

请尝试以下操作:

对于hasMany

return $this->hasMany(MonTC::class, 'montc_id');

对于belongsTo

return $this->belongsTo(MonHoc::class, 'monhoc_id');

另一个解决方案是:

return $this->hasMany('App\Models\MonTC', 'montc_id');

还有

return $this->belongsTo('App\Models\MonHoc', 'monhoc_id');

答案 1 :(得分:0)

检查:

public function test(MonHoc $monhoc){
   $monhoc = $monhoc->find(1) //the id that exists
   $mon=$monhoc->monTienQuyet;
   dd($mon);
}