首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Laravel 5 Eloquent 關聯關係實作:一對多與多對多

     編輯:PHP 綜合知識

Eloquent 關聯關係是 Laravel 最迷人功能之一。本文實作「一個用戶擁有多篇文章」、「一篇文章屬於一個用戶」的一對多關聯,並示範遷移外鍵建立與 Tinker 互動驗證。

1. 定義模型關聯

User 模型(一對多:擁有多篇文章)

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class User extends Model {
    public function articles() {
        return $this->hasMany('App\Article');
    }
}

Article 模型(屬於:單一用戶)

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Article extends Model {
    public function user() {
        return $this->belongsTo('App\User');
    }
}

2. 資料庫遷移加入外鍵

修改 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

3. Tinker 互動驗證關聯

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->articlesCollection(集合)直接取得關聯資料
$user->articles()Builder(查詢建構器)需進一步條件過濾、分頁等
$user->articles()->get()Collection等同 $user->articles

本文範例程式碼參考:GitHub 專案

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved