iT邦幫忙

2021 iThome 鐵人賽

DAY 7
1
Software Development

全端開發包括測試自己一條龍!系列 第 7

Day 7 - 淺談Laravel資料庫關聯的運用

當數據龐大時,我們不會把所有資料都存在同一個資料表,會依照資料類型做分類,例如:使用者資料的users table、文章資料的posts table,這時候資料的關聯就很重要,必須有方法讓我們知道這篇文章是哪個User所發布,所以在這邊簡單介紹Laravel Model要如何撰寫Relationship.

  1. 前一篇文章可以看到我們建立的database/migration/2021_09_19_082930_create_posts_table.php規劃了Post table有一個user_id欄位,就是為了能夠知道這篇文章是誰發的,來做資料庫的關聯
/**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->comment('發文者');
            $table->string('title')->unique()->comment('標題');
            $table->string('content')->comment('內文');
            $table->timestamps();
        });
    }
  1. 首先我們需要在User model加上hasMany的方法,由於一個使用者可以發多篇文章,此行為是一對多關係,所以選擇hasMany
# App/Models/User.php
/**
 * 取得使用者的文章
 */
public function posts()
{
    return $this->hasMany(Post::class);
}
  1. 我們往底層看,可以看到第二個參數是外鍵,因為我們第一個參數是Post model,預設指的是Post table的user_id = 外鍵,換句話說就是Post table user_id關聯了User table;第三個參數是Model本身的主鍵,預設指的就是uesr table的id.
/**
     * Define a one-to-many relationship.
     *
     * @param  string  $related
     * @param  string|null  $foreignKey
     * @param  string|null  $localKey
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function hasMany($related, $foreignKey = null, $localKey = null)
    {
        $instance = $this->newRelatedInstance($related);

        $foreignKey = $foreignKey ?: $this->getForeignKey();

        $localKey = $localKey ?: $this->getKeyName();

        return $this->newHasMany(
            $instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey
        );
    }
  1. 如此一來當我們只用到User model就可以直接使用這個function取得該使用者所發的文章
/**
 * 取得文章數量
 *
 * @return mixed
 */
public function getPostList()
{

    try {
        $user = Auth::guard('api')->user();
        $result = User::find($user->id);
        return $result->posts;
    } catch (Exception $e) {
        dd($e);
    }
}

其餘情境可以參考官方文件,寫得非常詳細,其實按照需求去置換function name就好


上一篇
Day 6 - Laravel 8.0 如何快速建立API
下一篇
Day 8 - Laravel Request validation
系列文
全端開發包括測試自己一條龍!10
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言