laravelsqlif语句

nnsrf1az  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(157)

我想在我的页面上显示所有产品。每个产品有x个图像。有些产品的图像设置为封面图像。现在我需要得到所有带有封面图像的产品,如果某个产品没有封面图像集,那么我需要得到一个随机图像。

+----+--------------+
| id | product_name | 
+----+--------------+
|  1 | Ferrari      |  
|  2 | Audi         |  
|  3 | BMW          | 
+----+--------------+

+----+--------------+------------+-------------+--+
| id |  image_name  | product_id | cover_image | 
+----+--------------+------------+-------------+
| 1  | audi.jpg     |          2 |           1 |  
| 2  | Audis.jpeg   |          2 |             |  
| 3  | bemms.jpg    |          3 |           1 |  
| 4  | ferrari.jpeg |          1 |             |  
| 5  | ferr.jpg     |          1 |             |  
+----+--------------+------------+-------------+

到目前为止,我已经尝试了这个代码,但它不能解决我的问题,因为我只得到封面图像集的图片。

public static function get_all_products() {
  return \DB::table('products')
      ->leftjoin('product_pictures', 'products.id', '=', 'product_pictures.product_id')
      ->select('products.name', 'product_pictures.images_name')
      ->where('product_pictures.cover_image', '=', 1)
      ->get();
}

欢迎任何帮助!

yjghlzjz

yjghlzjz1#

你可以自己加入 product_pictures 稍微调整一下table on 条款

select p.*, pp1.*
from products p
join product_pictures pp1 on p.id = pp1.product_id
left join product_pictures pp2 
      on  pp1.product_id =  pp2.product_id
      and case when pp1.cover_image is null
               then pp1.id > pp2.id
               else null 
          end
where pp2.product_id is null
order by p.id

演示

omqzjyyz

omqzjyyz2#

我要回答我自己的问题也许有人会面临同样的问题。我实际需要的sql查询:

select id, name, images_name from (
(select `products`.`id`, `products`.`name`,  `product_pictures`.`cover_image`, `product_pictures`.`image_name` 
from `products` 
left join `product_pictures` on `products`.`id` = `product_pictures`.`product_id` 
where `product_pictures`.`cover_image` = 1 OR `product_pictures`.`cover_image` IS NULL
group by `products`.`id`) 

UNION

select id, name, images_name from (
(select `products`.`id`, `products`.`name`,  `product_pictures`.`cover_image`, `product_pictures`.`image_name` 
from `products` 
left join `product_pictures` on `products`.`id` = `product_pictures`.`product_id` 
where `product_pictures`.`cover_image` = 0
group by `products`.`id`) 

    ) t
group by id

相关问题