简体   繁体   中英

How can i get all data in left table and related table data based on condition laravel

在此处输入图像描述 I have a product table with id,name,price and cart table with id,user_id,product_id,qty. I want all data in product table and related data in cart table where user_id is logged user_id .If no relation with cart i should get data in product table.

Table structure like this:

Based on your example I think you want something like:

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);

And you should use:

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM