i have two kind of product. game and game-time .
in my code. item_id
column of order_items
table, represents the id of target product (may be id of game_codes
or game_time_codes
)
and product_type_id
represents the id of product kind (number 1 for gameCode and 2 for gametime )
in my code im trying to show specific user orders with purchased items info.
i should join game_codes
when if product_type_id is 1
and join game_time_codes
when if product_type_id is 2
i wrote this query but it return null. how can i fix this?
$joinGCSub = DB::table("game_codes")->where("user_id", 1)->where("sold", 1);
$joinGTSub = DB::table("game_time_codes")->where("user_id", 1)->where("sold", 1);
$orders = DB::table('orders')
->leftJoin("order_items", "orders.id", "=", "order_items.order_id")
->leftJoin("product_types", "order_items.product_type_id", "=", "product_types.id")
->joinSub($joinGCSub, "gc" , function ($join){
$join->on('order_items.item_id', "=", "gc.id")->where("product_types.id", 1);
})->joinSub($joinGTSub, "gt", function($join) {
$join->on('order_items.item_id', "=", "gt.id")->where("product_types.id", 2);
})
->where("orders.user_id", 1)
->get();
dd($orders);
you can see tables structure below
order TABLE
id | user_id | .... etc
order_items table TABLE
id | order_id | product_type_id | item_id ...etc
game_codes TABLE
id | code | user_id | sold ... etc
game_time_codes TABLE
id | code | user_id | sold ...etc
Can write like below:
$joinGCSub = DB::table("game_codes")->where("user_id", 1)->where("sold", 1);
$joinGTSub = DB::table("game_time_codes")->where("user_id", 1)->where("sold", 1);
$query = DB::table('orders')
->leftJoin("order_items", "orders.id", "=", "order_items.order_id")
->leftJoin("product_types", "order_items.product_type_id", "=", "product_types.id");
if ($product_type_id == 1)
$query->joinSub($joinGCSub, "gc", function ($join) {
$join->on('order_items.item_id', "=", "gc.id")->where("product_types.id", 1);
});
if ($product_type_id == 2)
$query->joinSub($joinGTSub, "gt", function ($join) {
$join->on('order_items.item_id', "=", "gt.id")->where("product_types.id", 2);
});
$orders = $query->where("orders.user_id", 1)
->get();
dd($orders);
But it's better to use whereExist
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.