'Laravel Eloquent relationships with 3 Table

Laravel 3 Table

table_user

  • id
  • name

table_barang

  • id
  • iduser
  • name
  • statusbarang_id

table_statusbarang

  • id
  • name

My code UserModels:

public function BarangModels()
    {
        return $this->hasMany(BarangModels::class, 'iduser');
    }

My code BarangModel :

public function UserModels()
{
    return $this->belongsTo(UserModels::class);
}

public function StatusBarangModels()
{
    return $this->hasOne(StatusBarangModels::class, 'idstatusbarang');
}

My Code StatusBarangModels :

public function BarangModels()
{
    return $this->belongsTo(BarangModels::class);
}

My Code Usercontroller

public function showdetail($id)
{
    $value = UserModels::find($id);
    return view('user/detailuser', compact('value'));
}

And, I want to select barangmodels (id, name) statusbarangmodels (name) thank you



Solution 1:[1]

First you need to add primary key of BarangModel as foreign key in StatusBarangModels for the relationship that you define in models. After adding key use the following code.

UserModels::with(['BarangModels'=>function($item){
    $item->with(['StatusBarangModels'=>function($query){
      $query->select('statusbarang_id','name');
      }])->select('id','name');
 }])->get();

You need to select foreign key in nested relationships so that eloquent can match primary and foreign key in tables.

This will work. Thank you

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Navid Anjum