Joining Three Tables with Laravel Eloquent
Introduction
When working with relational databases, joining tables is often necessary to retrieve data across multiple tables. This article demonstrates how to join three tables in Laravel using the Eloquent ORM, offering an alternative to native SQL joins.
Database Schema
Consider the following database schema:
Querying with Eloquent
Relationship Setup
First, establish the relationships between the models:
// Article.php class Article extends Eloquent { public function user() { return $this->belongsTo('App\Models\User'); } public function category() { return $this->belongsTo('App\Models\Category'); } } // Category.php class Category extends Eloquent { public function articles() { return $this->hasMany('App\Models\Article'); } } // User.php class User extends Eloquent { public function articles() { return $this->hasMany('App\Models\Article'); } }
Join Query
To join the three tables and retrieve articles with their category and user details, use the with() method:
$articles = \App\Models\Article::with(['user', 'category'])->get();
Accessing Related Data
Once the results are retrieved, you can access the related data as properties:
foreach ($articles as $article) { echo $article->title . ' - '; echo $article->user->user_name . ' - '; echo $article->category->category_name; }
Conclusion
Using Eloquent to join tables simplifies and accelerates data retrieval in Laravel. By establishing relationships between models, you can easily access and manipulate related data.
The above is the detailed content of How to Join Three Tables in Laravel Using Eloquent?. For more information, please follow other related articles on the PHP Chinese website!