首页 > 解决方案 > 如何创建允许我查询两个表的一对多关系?

问题描述

我有两个模型ProductsProductImage.

我在模型中创建了一对多关系,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)
  1. 为什么查询试图将 where 条件应用于product_images表而不是products表?

  2. 我怎样才能达到获取所有产品及其相关图像的预期结果?

标签: laraveleloquent

解决方案


你可以做这样的事情

$products = Product::where('shown',1)->with('images')
->get();

此查询将获取显示的产品并急切加载每个产品的相关图像


推荐阅读