[英]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);
}
這將允許您在訪問其他 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.