如何创建允许我查询两个表的一对多关系?

How can I create a one to many relationship that allows me to query two tables?

我有两个模型 ProductsProductImage

我在 Product 模型中创建了一对多关系,如下所示:

public function images()
{
    return $this->hasMany(ProductImage::class);
}

我正在尝试从我的控制器中检索 product_images table 中的所有 'shown' 产品及其相关图像,如下所示:

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

我的 products table 中有一个 shown 列,但 product_images table 中没有,所以我收到此错误:

  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 table 而不是 products table?

  2. 如何才能得到所有产品及其相关图片的预期结果?

你可以这样做

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

此查询将获取显示的产品并预先加载每个产品的相关图片

$products = Product::where('shown',1)->with('product_images') ->获取(); product_id 列必须在 product_images table