Home Paket Belajar Bootcamp Instruktur

Kuasai Eloquent ORM #4 - Relasi Lanjutan: Has-Through

Pelajari Eloquent ORM Laravel dari dasar hingga mahir. Pahami berbagai jenis relasi seperti hasOne, hasMany, belongsTo, belongsToMany, hasManyThrough, hingga polymorphic relationship. Kuasai teknik query yang efisien menggunakan eager loading, constraint query, aggregate, subquery, serta cara menghindari N+1 Query agar aplikasi Laravel lebih cepat dan scalable. Materi disertai studi kasus dan best practice yang sering digunakan di proyek nyata.

✅ Telah dilihat 22 kali

Rating: 5.00 ⭐

... 08 June 2026, 19:34

hasManyThrough

Contoh kasus: Country ingin mengakses Post melalui User.

countries → users → posts
// countries
//   id, name

// users
//   id, country_id, name

// posts
//   id, user_id, title

Model Country:

class Country extends Model
{
    // Country punya banyak post melalui user
    public function posts(): \Illuminate\Database\Eloquent\Relations\HasManyThrough
    {
        return $this->hasManyThrough(
            Post::class,    // Model tujuan akhir
            User::class,    // Model perantara
        );
    }
}

Penggunaan:

$country = Country::find(1);

// Ambil semua post dari negara ini
$posts = $country->posts;

// Dengan eager loading
$country = Country::with('posts')->find(1);

hasOneThrough

Contoh kasus: Supplier mengakses AccountHistory melalui Account.

suppliers → accounts → account_histories
class Supplier extends Model
{
    public function accountHistory(): \Illuminate\Database\Eloquent\Relations\HasOneThrough
    {
        return $this->hasOneThrough(
            AccountHistory::class,
            Account::class,
        );
    }
}

Kustomisasi Key pada Has-Through

public function posts(): HasManyThrough
{
    return $this->hasManyThrough(
        Post::class,        // Final model
        User::class,        // Intermediate model
        'country_id',       // FK di tabel intermediate (users)
        'user_id',          // FK di tabel final (posts)
        'id',               // PK di tabel ini (countries)
        'id',               // PK di tabel intermediate (users)
    );
}

Ringkasan Episode 4

Method Kegunaan
hasManyThrough Akses koleksi data melewati satu model perantara
hasOneThrough Akses satu data melewati satu model perantara

Daftar eBook