使用Laravel Eloquent 模型連接三個表
在Laravel 中,使用Eloquent 模型簡化了數據關係的檢索。本文示範如何使用 Eloquent 連接三個表,以從文章、類別和使用者表中檢索資料。
考慮以下資料庫架構:
Articles Table | Categories Table | User Table |
---|---|---|
id | id | id |
title | category_name | user_name |
body | user_type | |
categories_id | ||
user_id |
目標是檢索文章及其對應的類別名稱(而不是category_id)和使用者名稱(而不是user_id)。
定義基於資料庫模式的模型之間的關係:
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'); } }
$articles = \App\Models\Article::with(['user','category'])->get();資料擷取 資料擷取
// Retrieve user name $article->user->user_name // Retrieve category name $article->category->category_name
資料擷取
$categories = \App\Models\Category::with('articles')->get(); $users = \App\Models\Category::with('users')->get();資料擷取資料擷取資料檢索資料的文章:用法如下存取相關資料:特定關係擷取擷取類別內或特定使用者的文章:結論Laravel 的Eloquent 模型大幅簡化了檢索關係資料的任務。透過了解模型之間的關係並在程式碼中設定它們,您可以輕鬆存取必要的資料並有效地執行更複雜的查詢。
以上是如何使用 Eloquent 關係在 Laravel 中連接三個表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!