繁体   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