iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 22
0
Software Development

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

Day22-Laravel新手基礎訓-Eloquent: Relationships-One to Many

胎嘎侯

接續昨日的主題,今天要了解的是1對多個關係(One to Many),也就是一個A實體會對應到多個B實體。待會的實例為:假定1個用戶會有多篇文章,同一張表裡的每篇文章只有1個用戶(無共同編輯)
image alt

One to Many

延續使用昨天的users資料表,只需另外創建一個新的Model與Migration即可。

php artisan make:model Post -m

進入posts資料表,添加兩個新的欄位後,進行php artisan migrate

$table->string('title');
$table->unsignedBigInteger('user_id');

確認欄位是否成功建立,接著我們要使用Factory快速建立幾筆假的Post資料。

php artisan make:factory PostFactory --model=Post

進入PostFactory,將下列欄位加入return之中:
這裡我們利用faker並指定要產出的假資料為sentence;另外,將所有的user資料表數據以亂數隨意指定id並存在post資料表的user_id裡。

$factory->define(Post::class, function (Faker $faker) {
    return [
        'title'=>$faker->sentence,
        'user_id'=>User::all()->random()->id,
    ];
});

到Tinker執行Factory的指令(如果您不熟tinker,可以照著試試看,這裡先不進行解釋)

php artisan tinker

進入後輸入指令(9指的是要產出9筆,指向create方法)

factory(App\Post::class,9)->create();

別忘了到資料庫確認假資料的產出哦~

兩個表的資料都建立好了,來做表的連結吧!

分解Eloquent的1對多關係

hasMany:每個用戶有數個posts
belongsTo:這些posts屬於同一個用戶

把下列資料分別輸入至User.php、Post.php
User.php

public function posts()
{
    //每個用戶有數個posts
    return $this->hasMany('App\Post'); //綁定與Post的關係(正向)
}

Post.php

    protected $fillable = ['title','user_id'];

public function user()
{
    //這些posts屬於同一個用戶
    return $this->belongsTo('App\User');
}

將1對多關係建立完成後,進入api.php增加要測試的路由。

建立一個get請求的路由,URI為/posts。

Route::get('posts',function(Request $request)
{
$posts = Post::where('user_id',3)->with('user')->get();
return $posts;
});

從Post(Model)中找user_id為3的資料,指向前面創建的user方法(這些posts屬於同一個用戶),我們來看Postman會返回什麼資料。
https://ithelp.ithome.com.tw/upload/images/20191007/20119022S6VDlskbCS.png
從資料庫來看:

  • 從Post(Model)中找user_id為3的資料。

    https://ithelp.ithome.com.tw/upload/images/20191007/20119022orlWwmumzS.png

  • 返回的是users 資料表的第1、7筆資料。

    https://ithelp.ithome.com.tw/upload/images/20191007/20119022HG3X2Pd3GI.png

今天1對多就先到這啦~明天見


上一篇
Day21-Laravel新手基礎訓-Eloquent: Relationships-One to One
下一篇
Day23-Laravel新手基礎訓-Eloquent: Many to Many (前言:創建多對多資料表,踩坑大全)
系列文
後端PHP+Laravel--新手實戰日記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言