Laravel hasOneThough & Laravel hasManyThough Relationships

Laravel
December 10, 20221 minuteuserVishal Ribdiya
Laravel hasOneThough & Laravel hasManyThough Relationships

Laravel HasOneTHough & Laravel HasManyThough Relationships

We generally know about the 4 basics Laravel Relations ships that laravel provides:

Now we are going to see the major missing relationships that we are thinking are "Hard to use", but in real cases, it's needed while developing a project.

Even though I was thinking that HasOneThough and HasManyThough Relationships were will be hard to understand, I was wrong. it's really easy to understand.

Understanding HasOneThough

Let's say there is a Library that wants to know the book issuer's name directly, in this case, we generally do :

  • Fetch Books
  • Fetch its related issuer by using the HasOne Relation

What if I say I can directly access the issuer name into the Library model, yes we can achieve this by using the has one though.

Library
- id
- name

Book
- id
- name
- library_id

Issuer
- id
- name
- book_id
public function issuer() {
    return hasOneThough(App\Issuer, App\Book, library_id, book_id)
}

Understanding HasManyThough

Let's say in the same example that there are multiple issuers of the same books, we can achieve it as follow.

public function issuer() {
    return hasManyThough(App\Issuer, App\Book, library_id, book_id)
}

Hope it will be helpful.

Thanks