Home > Software design >  How to retrieve data from eloquent laravel
How to retrieve data from eloquent laravel

Time:12-05

I have a relationship between 4 tables where the kontraks table is directly related to the skkos and vendors table.

But here I have a relationship between the skkos table and the units table. How to relate between skkos table and unit table? so i can retrieve unit->name from table units

{
  id: 1,
  periode: "TW III",
  nomor_kontrak: "nomor kontrak",
  tanggal_awal: "2021-12-04",
  tanggal_akhir: "2021-12-04",
  uraian_komitmen: "uraian",
  nilai_kontrak: 100000,
  created_at: "2021-12-04T12:33:32.000000Z",
  updated_at: "2021-12-04T12:33:32.000000Z",
      skko: {
          id: 1,
          unit_id: 1,
          kategori_id: 17,
          nomor_skko: "001/OPR/UID-LPG/2021/M",
          nomor_prk: "2021.PRK.PEG.UID.01.01",
          periode: "TW I",
          uraian_kegiatan: "Pemeliharaan Kesehatan",
          nilai_rekomendasi: 1374595806,
          nilai_penetapan: 1374595806,
          revisi: "0",
          tanggal: "2021-01-26",
          created_at: "2021-12-01T15:15:44.000000Z",
          updated_at: "2021-12-01T15:15:44.000000Z"
          },
     vendor: {
          id: 1,
          name: "Apotek Kimia Farma",
          created_at: "-000001-11-30T00:00:00.000000Z",
          updated_at: "-000001-11-30T00:00:00.000000Z"
          }
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

My eloquent relation:

$kontrak =  Kontrakao::with('skko','vendor')
            ->orderBy('id','DESC')
            ->get();

CodePudding user response:

You need to eager load the relation. Try:

$kontrak =  Kontrakao::with('skko.unit','vendor')
               ->orderBy('id','DESC')
               ->get();

CodePudding user response:

I have solved this with modify my model Kontrakao add this "->with('unit')" on skko method:

public function skko()
    {
        return $this->belongsTo(Skko::class)->with('unit');
    }

So in view i can call it with this:

{{$row->skko->unit->name}}
  • Related