laravel - 我如何在laravel中放置条件?
问题描述
我有存储我的图像的文件模型,我有商店模型,商店可以有很多图像,在商店模型中我写了这个代码:
public function Files()
{
return $this->hasMany('system\models\file', 'attachment_id');
}
我想用它的图像检索商店模型,现在我的问题是我怎样才能把条件放在哪里。我检索商店模型的代码是:
$shop = Shop::where('id', $id)->with('ShopType', 'User', 'Files')->get();
注意:我需要为调用 attachment_id 的 Files 方法中设置的主题之一的关系设置 2 个条件,而我的第二个条件是 attachment_type 请帮助我。谢谢
解决方案
您可以使用约束急切负载:
$shop = Shop::with(['ShopType','User', 'Files'=>function ($query)use($id)
{
query->where('id', $id);
}
])->get();
更多细节在:
https://laravel.com/docs/7.x/eloquent-relationships#constraining-eager-loads
推荐阅读
- python - 如何使用 python 将文件保存为原始文件名?
- c++ - 与 LPVOID 不兼容的参数类型
- javascript - 比较从提升状态更新数据(状态)的方式,应该还是不应该?
- sql - 如何在sql中提取没有时区的时间戳并且不将其转换为字符串进行操作?
- discord.js - Discord.js/ROBLOX API Endpoint 问题返回“Typeerror: json.data is not iterable”
- python - 如何将日期字符串转换为浮点数以表示 x 轴?
- python - 如何使用 python 监控实时响应并做出决定?
- android - 在我的颤振项目中升级到最新版本后出现 AndroidManifest.xml 错误
- css - React Native:防止边框使 View 变大
- hibernate - JPA @ManyToOne 连接列名时的场景在两个表中是相同的