Skip to content
Advertisement

How to join three table by laravel eloquent model

I have three table

Articles table

JavaScript

Categories table

JavaScript

User table

JavaScript

I want to show articles with their category name instead of category_id and user_name instead of user_id I try like these query It is work!

JavaScript

But I want to do by Eloquent way. Please, how could I do?

Advertisement

Answer

With Eloquent it’s very easy to retrieve relational data. Check out the following example with your scenario in Laravel 5.

We have three models:

  1. Article (belongs to user and category)

  2. Category (has many articles)

  3. User (has many articles)


  1. Article.php
JavaScript
  1. Category.php
JavaScript
  1. User.php
JavaScript

You need to understand your database relation and setup in models. The user has many articles. The category has many articles. Articles belong to user and category. Once you set up the relationships in Laravel, it becomes easy to retrieve the related information.

For example, if you want to retrieve an article by using the user and category, you would need to write:

JavaScript

and you can use this like so:

JavaScript

In another case, you might need to retrieve all the articles within a category or retrieve all of a specific user`s articles. You can write it like this:

JavaScript

You can learn more at http://laravel.com/docs/5.0/eloquent

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