Darama
Darama

Reputation: 3370

Has-Many-Through Relations

I have done a lot of research in Google about this. There are not a good examples with using this type of relation between models.

Can somebody share own sample using Has-Many-Through Relations in Laravel?

Upvotes: 0

Views: 73

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

Let's take a sample of a social network where you have User, their Friends and their friends' Photos. 3 models. yep a friend is just a normal user but for this example, a Friend would be a separate Model.

1- A user has friends

public function friends() {
    return $this->hasMany(Friend::class);
}

2 - A friend has photos

public function photos() {
    return $this->hasMany(Photo::class);
}

3 - You are the admin. you have many users, including John. John has a lot a friends. So sometimes, you want to see John's friends photos, maybe those where they tag him. So in user you define the relationship

public function friendsPhotos() {
    return $this->hasManyThrough(Friend::class, Photo::class); //could add a scope here for picture with tags only. 
}

Not problably the best example. But it shows how you can see all John's friends pictures by just doing

$john = User::where('email', '[email protected]')->first();
$john->friendsPhotos();

If the example doesnt suit you well, now think of a bank looking for their best salesperson in a specific Branch. A Branch hasMany Salesperson, and each Salesperson hasMany Customers they deal with.

In Branch model, you define

public function customers() {
    return $this->hasManyThrough(Salesperson::class, Customer::class);
}

I hope this helps a little bit.

Database tables for the banking system

1- Branch

id
name
...

2 - Salesperson

id
branch_id
firstname
...

3 - Customer

id
salesperson_id
firstname
...

Upvotes: 1

Related Questions