Joining Three Tables Using Laravel Eloquent Model
In Laravel, retrieving relational data is simplified with Eloquent models. This article demonstrates how to join three tables using Eloquent to retrieve data from the Articles, Categories, and Users tables.
Consider the following database schema:
Articles Table | Categories Table | User Table |
---|---|---|
id | id | id |
title | category_name | user_name |
body | user_type | |
categories_id | ||
user_id |
The goal is to retrieve articles along with their corresponding category name instead of the category_id, and user name instead of the user_id.
Define the relationships between the models based on the database schema:
Article.php:
namespace App\Models; use Eloquent; class Article extends Eloquent { protected $table = 'articles'; public function user() { return $this->belongsTo('App\Models\User'); } public function category() { return $this->belongsTo('App\Models\Category'); } }
Category.php:
namespace App\Models; use Eloquent; class Category extends Eloquent { protected $table = "categories"; public function articles() { return $this->hasMany('App\Models\Article'); } }
User.php:
namespace App\Models; use Eloquent; class User extends Eloquent { protected $table = 'users'; public function articles() { return $this->hasMany('App\Models\Article'); } }
To retrieve articles with related data:
$articles = \App\Models\Article::with(['user','category'])->get();
Access the related data as follows:
// Retrieve user name $article->user->user_name // Retrieve category name $article->category->category_name
To retrieve articles within a category or by a specific user:
$categories = \App\Models\Category::with('articles')->get(); $users = \App\Models\Category::with('users')->get();
Laravel's Eloquent models greatly simplify the task of retrieving relational data. By understanding the relationships between models and setting them up in your code, you can easily access the necessary data and perform more complex queries efficiently.
The above is the detailed content of How to Join Three Tables in Laravel Using Eloquent Relationships?. For more information, please follow other related articles on the PHP Chinese website!