Laravel Cart Sum based on input from 2 different tables - php

I have 2 tables Bag(cart) and products. I am saving quantity added by user in bad table and sale_price in products table. I need to get sum of bag.quantity * products.sale_price for each item. I am using query builder to get sum. How can i get that
I am able to use join to get list of all attributes
$items = DB::table('bag')->where('bag.user_id' , $user_id)->where('bag.order_id', 0)->join('products','products.id','=','bag.product_id')->get();
api link:
https://apptest.factory2homes.com/api/get-bag-products/3
I need to multiply quantity and sale_price for each unique product_id and then take total sum of it

you can use selectRaw to do such thing:
$items = DB::table('bag')->where('bag.user_id' , $user_id)
->where('bag.order_id', 0)
->join('products','products.id','=','bag.product_id')
->selectRaw('*, (bag.quantity * products.sale_price) as totalPrice')
->get();
and to get sum of all, you can use sum:
$sum=$items->sum('totalPrice');

Related

Sorting products by discount percentage

I am trying to sort products by discount percentage in my laravel app.
I have two columns in my products table i.e. price, discount_price. How can I order order them so that products with higher discount shows up higher in order. I've tried following but it doesn't work
$products = DB::table('products')->get();
$sorted_products = $products->sortBy('price - discount_price');
Any pointers plz, thanks.
You can use the select method and DB::raw to add a RAW SQL component to the query. Assunming that discount is the discount in currency units we are interested in fetching all the fields (*) plus the calculated field price - discount which we will call real_price.
$sorted_products = DB::table('product')
->select(DB::raw("*, price - discount as real_price"))
->orderBy("real_price")
->get();
This will build the following SQL query and execute it:
SELECT *, price - discount as real_price FROM product ORDER BY real_price;
If the discount is as percentage you could:
$sorted_products = DB::table('product')
->select(DB::raw("*, price * discount as real_discount"))
->orderBy("real_discount")
->get();
Which would be ordered by higher discount value.

Is there a way to check more than one matches with a minimum value from a relation table?

I have 2 relational tables "users" and "user_categories".(In user categories table 'user_id' and "category_id" is being saved)
Now I need to search users who has a common category matching with a percentage value.
More clearly, I am receiving 2 values in my request 1. array of Category Ids to be matched. 2. Percentage to be matched .
So If category_ids = array(1,2,3,4,5,6,7,8,9,10);
and percentage_value = '100%';
Then the out put should have all the users who match all the 10 category ids.
If percentage_value = '30%';
Then the out put should have all the users who match any 3 category ids.
Now If I use 'whereIn()' it returns the users who match minimum 1 value, which is not my required thing.
This is much complicated to make such query. Any help will be appreciated.
First, you should name your pivot table category_user to follow Eloquent naming conventions.
Second, take the intersection of the array of category ids received and the category ids associated with the user. Then calculate the percentage of the intersction / total and compare that against the threshold value:
// filter only users with at least "percentage_value" or greater matching category ids.
$users = User::all()->filter(function (User $user) {
$userCategoryIds = $user->categories->pluck('id')->toArray();
$ids = array_intersect(request()-get('category_ids'), $userCategoryIds);
return (count($ids) / count(request()->get('category_ids'))) >= request()->get('percentage_value');
});
I am not familiar with Eloquent but below is the sql syntax for the query with a ":givenPercentage" parameter to be bound with your percentage.
SELECT user_id
FROM (
SELECT user_id, COUNT(user_id) AS user_cats
FROM user_categories GROUP BY user_id) user_cat_count
WHERE
user_cats / (SELECT count(category_id) FROM categories) > :givenPercentage
You are effectively creating a subquery to count the number of categories each user is in. Then you are comparing the counts with the total categories in the where clause and checking if it is above a certain percentage.

Laravel 5.5 groupBy with sum and first option

I have a table with some same id so I display them groupBy option with sum. I have many column like id, item_name, rate, quantity, value Here is my code.
$orders = Order::where('item_id', $id)
->where('delivery_status', 1)
->groupBy('item_id')
->selectRaw('sum(quantity) as quantity, sum(value) as value, item_id')
->pluck('item_id','quantity', 'value');
By this I got three column with id and quantity and value with sum. My problem is that I also want to display other column like item_name, rate, delivery_status etc. and I don't want to sum them like rate. How can I display them? I can groupBy also with item_name and it works but can not group with rate because other items may also have same rate.
Don't use pluck, as that will only return the columns you have specified. Instead, try using get to return all the table columns:
$orders = Order::where([
'item_id' => $id,
'delivery_status' => 1
])
->groupBy('item_id')
->selectRaw('orders.*, sum(quantity) as quantity, sum(value) as value, item_id')
->get();

How get needed rows from 3 table in Laravel 5.5

I have 3 tables, Order, Products, Order_Products. I need get all field from order and products, thats ok using hasManyThrough(). But i need 1 more field from Order_products. How can i get this field ?
public function products()
{
//in order model
return $this->hasManyThrough('App\Models\Product','App\Models\OrderProduct','order_id','id','id','product_id');
}
using sql i need query like
SELECT
products.*, order_products.order_id, order_products.count as order_count
FROM
products
INNER JOIN order_products ON order_products.product_id = products.id
WHERE
order_products.order_id = 2
You can access intermediate table fields by using pivot attribute on model.
Lets say you have product, Then you can access count field of orders_products
$product->pivot->count;

updating sql values with array which have a couple times occured items

While i am coding a shopping site, I need to update product stock.
But the thing is, naturally shopping cart can have the same items a couple of times.
What is the best way for updating it?
I tried IN but the following SQL query returns 3 items.
SELECT *
FROM `products`
WHERE id
IN ( 3, 4, 4, 6 )
LIMIT 0 , 30
Here is my solution but, I don't think this is the best one.
$cart = array(1,3,4,4,5,8,22,22);
$itemlist = array_count_values($cart);
foreach($itemlist as $itemid=>$ocurrence){
$SQL = "UPDATE products SET stock = stock-".$ocurrence." WHERE id = ".$itemid;
mysql_query($SQL);
}
You can do something like this:
SELECT * FROM menu WHERE item_id = 1
UNION ALL
SELECT * FROM menu WHERE item_id = 1
UNION ALL
SELECT * FROM menu WHERE item_id = 2
Check this link:
MySQL table -> Can you return the same row multiple times, in the same query?
if possible create a seperate item_cart, table which will have (cart_id, item_id , product_id) as primary key. from here you can get do a group by on product_id to see how many no of product sold.
select product_id, count(product_id) as "No of Product Sold" from item_cart
group by product_id
your php code will update no of products in stock coloumn perfectly.
If possible you try setting triggers for updatin stock columns whenever any product is sold.

Categories