laravel - 如何创建允许我查询两个表的一对多关系?
问题描述
我有两个模型Products
和ProductImage
.
我在模型中创建了一对多关系,Product
如下所示:
public function images()
{
return $this->hasMany(ProductImage::class);
}
从我的控制器中,我试图在product_images
表中检索所有“显示”的产品及其相关图像,如下所示:
$products = Product::find(1)->images()
->where('shown', 1)
->get();
我的表中有一个shown
列,products
但表中没有,product_images
所以我收到此错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'shown' in
'where clause' (SQL: select * from `product_images` where
`product_images`.`product_id` = 1 and `product_images`.`product_id` is not
null and `shown` = 1)
为什么查询试图将 where 条件应用于
product_images
表而不是products
表?我怎样才能达到获取所有产品及其相关图像的预期结果?
解决方案
你可以做这样的事情
$products = Product::where('shown',1)->with('images')
->get();
此查询将获取显示的产品并急切加载每个产品的相关图像
推荐阅读
- javascript - JS DOM innerHTML 值不改变 HTML
- regex - 为什么这个正则表达式不匹配我的换行符分隔键=值对?
- python - python中分号的使用?
- django - 保存后如何对文章执行解析和编辑功能?
- webusb - WebUSB 无法在某些 android 设备上声明设备
- javascript - HTML 音频:访问 MP3 章节标记
- graphql - 从 Prisma 中的多对多表中获取元信息
- python - 使用python在表中除和很多值
- python - Python docx 替换段落中的字符串,同时用句点保持样式
- python - Jupyter Notebook 仍在运行或死机