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

Time:10-30

I have two models Products and ProductImage.

I've created a one to many relationship in the Product model as follows:

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

From my controller, I'm trying to retrieve all 'shown' products and their related images in the product_images table as follows:

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

There is a shown column in my products table but not in the product_images table so I'm getting this error:

  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. Why is the query trying to apply the where condition to the product_images table as opposed to the products table?

  2. How can can I achieve the desired result of getting all products and their related images?

CodePudding user response:

you can do something like this

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

This query will get the shown products and eager load the related images for each product

CodePudding user response:

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

The column product_id must be in product_images table

  • Related