Eloquent Approach for Joining Three Tables
Problem:
Consider three tables: Articles, Categories, and Users. The objective is to retrieve Articles with their Category name and User name instead of their respective IDs.
Solution:
Eloquent offers a straightforward method to retrieve relational data.
Model Definition:
// 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'); } }
Eloquent Query:
To retrieve Articles with Category and User information:
$article = \App\Models\Article::with(['user','category'])->first();
Usage:
To access the related data:
$article->user->user_name //Retrieve user name $article->category->category_name //Retrieve Category name
Other Examples:
$categories = \App\Models\Category::with('articles')->get();
$users = \App\Models\Category::with('users')->get();
Additional Resources:
The above is the detailed content of How to Retrieve Articles with Category and User Information using Eloquent?. For more information, please follow other related articles on the PHP Chinese website!