簡體   English   中英

如何修改 Laravel model 集合?

[英]How to modify Laravel model collection?

我有 2 個數據庫表。 第一個表是具有到服務器上files的鏈接(和其他參數)的文件。 第二個表有一個file_id列,用於存儲files表中文件所在行的 id。 如何在查詢 model 時從表files中創建連接元素。 獲取集合並在循環中添加圖像是不合適的。 我需要在訪問 model(不是 __construct ())時調用的 function 之類的東西,作為訪問器,但用於收集

您可以預先加載該關系,以便將文件作為包含file_id的 Model 的一部分。

在具有file_id的 Model 上,為File model 添加hasOne關系:

public function file()
{
    return $this->hasOne(File::class);
}

https://laravel.com/docs/8.x/eloquent-relationships#one-to-one

您可以在File model 上定義逆:

public function otherModel()
{
    return $this->belongsTo(OtherModel::class);
}

https://laravel.com/docs/8.x/eloquent-relationships#one-to-one-defining-the-inverse-of-the-relationship

這將允許您在訪問其他 model 時急切加載File

您可以使用with()方法急切加載 go :

$otherModel = OtherModel::with('file')->...

https://laravel.com/docs/8.x/eloquent-relationships#nested-eager-loading-morphto-relationships

或者,每次訪問其他 model 時,通過將$with添加到 model 來急切加載:

protected $with = ['file'];

https://laravel.com/docs/8.x/eloquent-relationships#eager-loading-by-default

--

然后,您將獲得該File作為其他 Model 的一部分,如下所示:

[
    'id' => 1,
    'file_id' => 4,
    'file' => [
        'id' => 11,
         ...,
    ],
    ...,
],

--

此外,由於您已經定義了反向關系,您可以在使用with()訪問File時急切加載另一個 model ;

$file = File::with('otherModel')->...

或者如上圖,在 model File中默認預加載:

protected $with = ['otherModel'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM