i have one to many relationship in my models and it works as i want, but sometime i only need one record to be returned (not as an array of collection). Here is my controller
$sesi = Sesi::with('jadwal.mapelLokal.guru','jadwal.mapelLokal.matapelajaran')->whereHas('jadwal',function($jadwal) use ($r) {
$jadwal->whereHas('mapelLokal',function($mapel) use($r) {
$mapel->where('id_lokal',$r->lokal);
});
})->get();
Sesi Model
class Sesi extends Model
{
protected $table = 'sesi';
public $timestamps = false;
public function jadwal()
{
return $this->hasMany('SIAStar\Jadwal','id_sesi');
}
}
jadwal model
class Jadwal extends Model
{
protected $table= 'jadwal';
public $timestamps = false;
public function mapelLokal()
{
return $this->belongsTo('SIAStar\MapelLokalGuru','id_mapel_lokal');
}
}
and MapelLokalGuru
class MapelLokalGuru extends Model
{
protected $table = 'mapel_lokal_guru';
protected $fillable = ['id_lokal','mapel_id','guru_id'];
public $timestamps=false;
public function mataPelajaran()
{
return $this->belongsTo('SIAStar\MataPelajaran','mapel_id');
}
public function guru()
{
return $this->belongsTo('SIAStar\Guru','guru_id');
}
public function formNilai()
{
return $this->hasMany('SIAStar\FormNilai','id_mapel_lokal');
}
public function lokal()
{
return $this->belongsTo('SIAStar\Lokal','id_lokal');
}
public function postMateri()
{
return $this->hasMany('SIAStar\PostKelasOnline','id_mapel_lokal');
}
}
and the result of controller is like this
Collection {#454 ▼
#items: array:2 [▼
0 => Sesi {#452 ▼
#table: "sesi"
//...
#relations: array:1 [▼
"jadwal" => Collection {#468 ▼
#items: array:1 [▶]
}
]
}
]
}
as you se, jadwal relationship returning a collection, but what i want is only single record since it's only has one record. How to querying nested relationship so jadwal relationship only return one data?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire