Skip to content
Advertisement

hasManyThrough laravel relation

I have three table below.

JavaScript

hasManyThrough in Country::class model to get all products.

JavaScript

I want products which are related to countries or one country:

JavaScript

Advertisement

Answer

The relation you’re describing best suits a many to many, which is usually written in Laravel as a belongsToMany on both sides.

JavaScript

If you stick to Laravel’s naming conventions:

  • Rename product_countries to country_product.
  • In country_product use country_id instead of country_code.

…you should be able to access the relations in the way you expect:

JavaScript

If you don’t want to stick to the conventions, you are able to customise how you define the relationships. See Laravel’s documentation for further details.


In your case, to specify your relations using your custom table name and the custom field names you can do this:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement