iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 25
1
Software Development

後端PHP+Laravel--新手實戰日記系列 第 25

Day25-Laravel新手基礎訓-Eloquent: Many to Many 關係綁定

胎嘎侯~

今天終於進入Many to Many 的關係綁定,先回到Day23-Eloquent: Many to Many (前言:創建多對多資料表,踩坑大全),複習一下實作的例子。
一個user會有多個video的借閱紀錄,而且每個video都與多個用戶有關。

Many to Many

分解Eloquent的多對多關係,多對多皆使用belongsToMany方法。

  • belongsToMany:每個用戶有數個video的紀錄
  • belongsToMany:video的紀錄屬於多個用戶

昨天建立的測試數據-user資料、video資料及借閱紀錄,現在可以實際派上用場。
把下列資料分別輸入至User.php、Video.php

User.php

    public function videos()
    {
        //每個用戶有數個video的紀錄
        return $this->belongsToMany('App\Video')->withPivot('days'); //綁定與Video的關係
    }

希望顯示'days'的值,這裡增加withPivot方法定義特定欄位。

Video.php

class Video extends Model
{
    protected $fillable = ['name'];

    public function users()
    {
        //video的紀錄屬於多個用戶
        return $this->belongsToMany('App\User'); //綁定與User的關係
    }
}

新增UserVideoController

php artisan make:controller UserVideoController

記得要在上方引入3個Model名稱哦!

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\Video;
use App\UserVideo;

class UserVideoController extends Controller
{
    public function index()
    {
        $records = User::with('videos')->get();

        return $records;
    }
}

同場加映:Eager Loading
預設情況下的Eloquent是消極式的載入,當我們載入了一個模型實例,與他相關的模型不會被載入,被呼叫才會被載入。如果使用消極式的載入,多對多關係綁定就不是那麼必須,因為多數時間我們會希望能帶出關係載入的模型。使用積極載入with()方法與get函式可以帶出與項目有關的項目。

$records = User::with('videos')->get();

從User模型帶出videos表,使用with方法指定要加載哪些關係,get為取得查詢的所有結果。

建立測試路由

Route::get('/records','UserVideoController@index');

進到Postman測試

耶,成功!花了三天的Many to Many 說明終於結束啦~~
明天見/images/emoticon/emoticon42.gif


上一篇
Day24-Laravel新手基礎訓-Eloquent: Many to Many (Factory 與 Tinker)
下一篇
Day26-Laravel新手基礎訓-Database: Seeding 埋下資料種子
系列文
後端PHP+Laravel--新手實戰日記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言