Laravel 8 一對多

2021-07-19 11:34 更新

一對多關(guān)聯(lián)用于定義單個模型擁有任意數(shù)量的其它關(guān)聯(lián)模型。例如,一篇博客文章可能會有無限條評論。正如其它所有的 Eloquent 關(guān)聯(lián)一樣,一對多關(guān)聯(lián)的定義也是在 Eloquent 模型中寫一個方法:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * 獲取博客文章的評論
     */
    public function comments()
    {
        return $this->hasMany('App\Models\Comment');
    }
} 

記住一點,Eloquent 將會自動確定 Comment 模型的外鍵屬性。按照約定,Eloquent 將會使用所屬模型名稱的「Snake Case」形式,再加上 _id 后綴作為外鍵字段。因此,在上面這個例子中,Eloquent 將假定 Comment 模型對應(yīng)到 Post 模型上的外鍵就是 post_id。

一旦關(guān)系被定義好以后,就可以通過訪問 Post 模型的 comments 屬性來獲取評論的集合。記住,由于 Eloquent 提供了「動態(tài)屬性,因此我們可以像訪問模型的屬性一樣訪問關(guān)聯(lián)方法:

$comments = App\Models\Post::find(1)->comments;

foreach ($comments as $comment) {
    //
} 

當然,由于所有的關(guān)聯(lián)還可以作為查詢語句構(gòu)造器使用,因此你可以使用鏈式調(diào)用的方式,在 comments 方法上添加額外的約束條件:

$comment = App\Models\Post::find(1)->comments()->where('title', 'foo')->first(); 

正如 hasOne 方法一樣,你也可以通過向 hasMany 方法傳遞附加參數(shù)來覆蓋默認的外鍵和本地鍵:

return $this->hasMany('App\Models\Comment', 'foreign_key');

return $this->hasMany('App\Models\Comment', 'foreign_key', 'local_key'); 
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號