I have 3 Models:
MonHoc Model:
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 model:
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 model:
class MonTQ extends Model{
protected $table='montienquyet' ;
protected $fillable = [
'monhoc_id', 'montq_id',
];
public function monhoc(){
return $this->belongsTo('App\MonHoc','monhoc_id');
}
}
but when I use MonHoc model in controller:
public function test(MonHoc $monhoc){
$mon=$monhoc->monTienQuyet->toSql();
dd($mon);
}
it show SQL
select * from `montienquyet` where `montienquyet`.`montq_id` is null and `montienquyet`.`montq_id` is not null
It show null in MySQL because the where clause is the opposite. I don't know why the model export this SQL!
Please help!
Please try this one:
For hasMany
:
return $this->hasMany(MonTC::class, 'montc_id');
For belongsTo
:
return $this->belongsTo(MonHoc::class, 'monhoc_id');
Another solution is:
return $this->hasMany('App\Models\MonTC', 'montc_id');
And
return $this->belongsTo('App\Models\MonHoc', 'monhoc_id');
Check this:
public function test(MonHoc $monhoc){
$monhoc = $monhoc->find(1) //the id that exists
$mon=$monhoc->monTienQuyet;
dd($mon);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.