mercredi 21 novembre 2018

Eloquent ORM relationship always return null in laravel

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

-and 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 will show null in mysql beacuse the where clause is the opposite. i dont know why the model export this sql!

Please help!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire