I've searched a lot and can't find a solution. I have 3 tables, one shopping_carts table, one product and finally an items table. I have created an eshop and I want to display the quantity of each product after a user clicks the add to cart button. My code is below but that returns only the product that exists in items table and it's logic. I need the quantity of that product in items table but I need also the rest products from the products table.
return $query = Product::select('title','price','imageUrl','quantity','products.id')
->join('items','items.product_id','=','products.id')
->where('shopping_cart_id', '=' ,$id)->get();
You can achieve this in two ways:-
First one is by using relationships from here https://laravel.com/docs/5.7/eloquent-relationships
The second one is by modifying your existing query:-
return $query = Product::select('title','price','imageUrl','quantity','products.id')
->leftJoin('items','items.product_id','=','products.id')
->where('shopping_cart_id', '=' ,$id)->get();
Try this
$products = DB::table('items')
->join('products', 'items.product_id', '=', 'products.id')
->where('shopping_cart_id', '=' , $id)
->get();
Or Using relationships
class ShoppingCart extends Model
{
public function items()
{
return $this->hasMany('App\Item');
}
}
class Item extends Model
{
public function product()
{
return $this->belongsTo('App\Product');
}
}
then use
$shopping_cart = ShoppingCart::with(['items', 'items.product'])->find($id);
Updated answer with all product
Product::select('products.id', 'products.title', 'products.price', 'products.imageUrl',
DB:raw('(CASE WHEN items.qunatity IS NULL THEN 0 ELSE items.qunatity END) as quantity')
->leftJoin('items', function($join) use($id){
$join->on('products.id', '=', 'items.product_id')
->on('items.shopping_cart_id', '=', $id);
})->get();
i found the answer with some changes to noufalcep code
return Product::select('products.id', 'products.title', 'products.price', 'products.imageUrl',
DB::raw('CASE WHEN items.quantity IS NULL THEN 0 ELSE items.quantity END as quantity'))
->leftJoin('items', function($join) use($id){
$join->on('products.id', '=', 'items.product_id')
->where('items.shopping_cart_id', '=', $id);
})->get();