【问题标题】:How can i get all data in left table and related table data based on condition laravel如何根据条件 laravel 获取左表中的所有数据和相关表数据
【发布时间】:2023-03-23 20:43:01
【问题描述】:

我有一个带有 id 、name 、price 的产品表和一个带有 id 、user_id 、product_id 、qty 的购物车表。 我想要产品表中的所有数据和购物车表中的相关数据,其中 user_id 记录了 user_id。如果与购物车没有关系,我应该在产品表中获取数据。

表结构如下:

【问题讨论】:

  • 嗨!请在您的描述中包含您想要的输出。如果可能的话,还有带有样本数据的表结构。谢谢
  • @ErrBon 更新
  • 你应该使用left join。请记住,您想要所有信息的表格始终是第一位的。
  • 最好将表格结构添加为文本而不是图像..

标签: php mysql laravel


【解决方案1】:

根据你的例子,我认为你想要这样的东西:

create table product (
id int(9) not null auto_increment,
name varchar(20),
Primary key id(`id`)
);

insert into product values (1,'mobile'),(2,'tv'),(3,'fridge');

create table cart (
id int(9) not null auto_increment,
product_id int(9) ,
qty int(9) ,
user_id int(9) ,
Primary key id(`id`)
);

insert into cart values (1,1,1,1),(2,1,1,2);

你应该使用:

select p.*,c.* from product p left join cart c on p.id=c.product_id and c.user_id=1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 2023-04-06
    相关资源
    最近更新 更多