Eloquent 關聯關係是 Laravel 最迷人功能之一。本文實作「一個用戶擁有多篇文章」、「一篇文章屬於一個用戶」的一對多關聯,並示範遷移外鍵建立與 Tinker 互動驗證。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
public function articles() {
return $this->hasMany('App\Article');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model {
public function user() {
return $this->belongsTo('App\User');
}
}
修改 create_articles_table.php:
Schema::create('articles', function(Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned(); // 外鍵欄位
$table->string('title');
$table->text('body');
$table->timestamp('published_at');
$table->timestamps();
// 建立外鍵約束
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
開發階段可直接修改遷移檔後
php artisan migrate:refresh重建;上線專案應建立新遷移檔。
執行重建:
php artisan migrate:refresh
# 輸出範例
Rolled back: 2015_03_28_050138_create_article_table
Rolled back: 2014_10_12_100000_create_password_resets_table
Rolled back: 2014_10_12_000000_create_users_table
Nothing to rollback.
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrated: 2015_03_28_050138_create_article_table
Migrated: 2015_03_28_051200_add_excerpt_to_articels_table
php artisan tinker
Psy Shell v0.4.1 (PHP 5.4.16 — cli) by Justin Hileman
# 建立用戶
>>> $user = new App\User;
>>> $user->name = 'zhang jinglin';
>>> $user->email = 'zjl@example.com';
>>> $user->password = bcrypt('pass');
>>> $user->save();
=> true
# 查詢用戶
>>> App\User::first()->toArray();
=> ["id" => "1", "name" => "zhang jinglin", ...]
# 暫時在表單隱藏 user_id=1,並加入 $fillable
# 新增文章後驗證關聯
# 取得用戶所有文章(注意:關聯屬性 vs 關聯方法)
>>> $user = App\User::first();
>>> $user->articles->toArray(); // 正確:取得集合
>>> $user->articles()->get()->toArray(); // 同義:鏈式查詢
# 為什麼用 $user->articles 而非 $user->articles()?
# $user->articles() 回傳關聯查詢建構器,可進一步鏈式:
>>> $user->articles()->where('title', 'User 1 Article')->get();
# 反向:透過文章取得用戶
>>> $article = App\Article::first();
>>> $article->user; // 直接取得 User 物件
| 語法 | 回傳型別 | 用途 |
|---|---|---|
$user->articles | Collection(集合) | 直接取得關聯資料 |
$user->articles() | Builder(查詢建構器) | 需進一步條件過濾、分頁等 |
$user->articles()->get() | Collection | 等同 $user->articles |
本文範例程式碼參考:GitHub 專案