I have problem with my projects e-commerce
in,in this problem i have 2 tables.
Table Products
ID | Name_products | Price
P1 | Product A | 2000
P2 | Product B | 5000
P3 | Product C | 7500
Table User Carts
ID | User_id | Product_id | Quantity
C1 | User1 | P1 | 2
C2 | User1 | P2 | 1
I have using this query eloquent :
$totalPricec = MyCart::where('user_id', Auth::user()->id)
->select('products.nama_produk', 'products.id as product_id','products.price''my_carts.quantity','my_carts.id as id')
->join('products', 'products.id', '=', 'my_carts.product_id')
->sum('price');
but i got price is 7000 (product A = 2000 + product B = 5000)
should be 9000 (product A = 2000 * 2 + product B = 5000 * 1)
how i can get the total price actually?
I using this query
$totalPricec = MyCart::where('user_id', Auth::user()->id)
->select('products.nama_produk', 'products.id as product_id','products.price''my_carts.quantity','my_carts.id as id')
->join('products', 'products.id', '=', 'my_carts.product_id')
->sum(DB::raw('products.price * my_carts.quantity'));
and thats work :)
thank you for user #user3532758
Related
I have 2 tables, products and stocks. Each product has a stock record foreign key product_id in the stocks table. Each stock record has a quantity column.
Fields in the stocks table look like,
id | product_id | color_id | quantity
In brief: 1 product can have many stock records. I'm trying to get the product and its total count in the quantity column of stock records. Imagine product A (product id is 1) has 3 stock records in the stocks table like this,
id | product_id | color_id | quantity
1 | 1 | 3 | 10
2 | 1 | 4 | 20
3 | 1 | 2 | 40
Here for product A the total of quantity column in the stocks table is 10 + 20 + 40 = 70. I'm expecting to return this 70 and the product record.
Here is my code. I have no idea how to get that,
return DB::table('products')
->join('stocks', 'products.id', '=', 'stocks.product_id')
->paginate(5);
If your joins are correct use sum() with groupBy() clause
->select(DB::raw("SUM(stocks.quantity) as stocks_quantity"))
->groupBy('stocks.product_id') # or ->groupBy('products.id')
DB::table('products')
->join('stocks', 'products.id', '=', 'stocks.product_id')
->select(DB::raw("SUM(stocks.quantity) as stocks_quantity"))
->groupBy('products.id') #or groupBy('stocks.product_id')
->paginate(5);
Edit 01
DB::table('products')
->join('stocks', 'products.id', '=', 'stocks.product_id')
->select('products.*')
->selectRaw("SUM(stocks.quantity) as stocks_quantity")
->groupBy('stocks.product_id')
->get(5);
Edit 02
add 'products.id' in select
DB::table('products')
->leftjoin('stocks', 'products.id', '=', 'stocks.product_id')
->select('products.id','products.*')
->selectRaw("SUM(stocks.quantity) as stocks_quantity")
->groupBy('products.id')
->get(5);
I have two three tables:
// invoices
+----+----------------+
| id | invoice_code |
+----+----------------+
| 1 | d09823r230r4 |
| 2 | 34tf354f45tf |
+----+----------------+
// commodities
+----+-------------+------------+--------+
| id | invoice_id | product_id | number |
+----+-------------+------------+--------+
| 1 | 1 | 1 | 2 |
| 2 | 1 | 3 | 4 |
+----+-------------+------------+--------+
-- number columns is the number of each ordered product in the invoice
// products
// invoices
+----+-----------+---------+
| id | name | price |
+----+-----------+---------+
| 1 | SFX-300 | 15000 |
| 2 | GB32-b10 | 2000 |
| 3 | SVX-m30 | 1200 |
+----+-----------+---------+
All I need to do is calculating the total price of an invoice. Here is the formula to calculate the total price for invoice x:
$total_invoice_price = 0;
foreach( $invoice_x->commodities as $commodity){
$total_invoice_price += ( $commodity.number * <products.price> )
}
echo $total_invoice_price;
The problem is about getting <products.price>. It needs one more join to products table. Any idea how can I do that using Laravel relationships ?
If you just need the total price, this could be done in pure sql with aggregate statements and joins over the three tables.
SELECT invoice.invoice_code, SUM(product.price * commodities.number)
FROM invoice
JOIN commodities ON invoice.id = commodities.invoice_id
JOIN product ON product.id = commodities.product_id
GROUP BY invoice.id
To save the query, you should do eager loading using "with()" the model you wish to join.
I'm not sure how you named your model and how well it linked to each other.
Let's assume that it've been done in the conventional way.
Here is the script.
$total_invoice_price = $invoice_x->commodities
->with('products')
->get()
->map(function ($commodity) {
return $commodity->number * $commodity->product->price;
})
->sum();
What I've done is after getting the products joined with each commodity. I do the get() to have the commodities collection. The from the collection, we do map on each commodity and return the number and price of product. Then we multiply and return as the sum of each commodity record. After that we sum all the totals to the grand total and get your result.
I wrote the code without testing, so try to adjust it to your code.
Please check below Query
$invoices_total = DB::table('invoices')
->join('products', 'invoices.id', '=', 'commodities.invoice_id')
->join('commodities', 'products.id', '=', 'commodities.product_id')
->sum('products.price * commodities.number')
->groupBy('invoices.id')
->get();
What is the way to sort a MYSQL result from multiple tables?
I have two tables. The first:
"store_products" table:
+----+-----------+
| id | name |
+----+-----------+
| 1 | Product 1 |
| 2 | Product 2 |
| 3 | Product 3 |
+----+-----------+
Here i placed product names. Other table contains prices for different product variants:
"store_products_variants" table:
+-----+------------+-------------+-------------+
| id | product_id | price_sale | ordering |
+-----+------------+-------------+-------------+
| 5 | 1 | 06.00 | 2 |
| 6 | 1 | 32.00 | 3 |
| 11 | 1 | 56.00 | 1 |
| 14 | 2 | 09.00 | 1 |
| 44 | 3 | 15.00 | 1 |
+-----+------------+-------------+-------------+
I need to create a sort on price (lowest and highest), that uses only first variant - ordered by column "ordering" from "store_products_variants" table.
From example above, the results should be:
+---+------------+---------------+
| 1 | Product 2 | (price 09.00) |
| 3 | Product 3 | (price 15.00) |
| 2 | Product 1 | (price 56.00) |
+---+------------+---------------+
Is this possible in MySQL?
Use the ordering column to join the correct variant onto the product.
This would be the query if the correct ordering value was always the 1.
SELECT
products.name,
variants.price_sale
FROM store_products AS products
INNER JOIN store_products_variants AS variants
ON variants.product_id = products.id
AND variants.ordering = 1
ORDER BY variants.price_sale ASC
This query will first look for the lowest ordering value of a product. Then use it to join the price on your result:
SELECT
products.name,
variants.price_sale
FROM
store_products AS products
INNER JOIN (
SELECT
product_id,
MIN(ordering) AS ordering
FROM
store_products_variants
GROUP BY
product_id
) AS variantOrdering
ON variantOrdering.product_id = products.id
INNER JOIN store_products_variants AS variants
ON variants.product_id = variantOrdering.product_id
AND variants.ordering = variantOrdering.ordering
ORDER BY
variants.price_sale ASC
select t.* from(
select t1.[id], t1.[name],
'(price ' + cast(max(t2.[price_sale]) as varchar(50)) + ')' as [price]
from [#store_products] t1
left join [#store_products_variants] t2
on t1.[id] = t2.[]product_id
group by t1.[id], t1.[name]
)t
Order by len(t.[price]), t.[price];
Yes this is possible. Try to use the JOIN command, and JOIN on the ID of each table.
Hello this is possible please use this query
SELECT p.id,p.name,spv.price_sale
from products p
INNER JOIN store_products_variants spv ON spv.product_id = p.id
where spv.ordering = 1
group by p.id
order by spv.price_sale asc
i think it gives the result what you want
I have a variable called $category which a user selects. On submit I need to look inside a table (profiles) for where the $category matches and pull back all of those profiles then look into the likes table and return all matching records for the returned profiles.
My database looks like:
TABLE: profiles
ID | username | category
-------------------------
1 | x | band
2 | y | airline
3 | z | airline
TABLE: likes
ID | account_id | likes | created_at
---------------------------------------
1 | 2 | 1000 | 21/03/2016
2 | 2 | 2000 | 22/03/2016
3 | 1 | 3000 | 22/03/2016
My code is the following:
$category = "band";
$profiles = DB::table('profiles')
->join('likes', 'profiles.id', '=', 'likes.account_id')
->where('category', '=', $category)
->select('profiles.*', 'likes.likes', 'likes.created_at')
->get();
account_id in the likes table will be the same as id in the profiles table. Also there maybe multiple like records for each profile.
The query just doesn't seem to work and it returns nothing back. I'm using laravel 5.2.
$profiles = DB::table('profiles')
->leftJoin('likes', 'profiles.id', '=', 'likes.account_id')
->where('profiles.category', '=', $category)
->select('profiles.*', 'likes.likes', 'likes.created_at')
->get();
I want to get all the purchases and their sums and also I don't want to add the amount if payments.deleted_at is not null.
Here are the tables
purchases
id | name
1 | Gamerzone Book
2 | Recipe Book
3 | EngineX Book
payments
id | purchase_id | amount | deleted_at
1 1 100 2015-06-12 11:00:00
2 2 50 NULL
2 2 10 NULL
Code
$query = DB::table('purchases')
->select(['purchases.*',
DB::raw("IFNULL(sum(payments.amount),0) as total")
])
->leftJoin('payments','payments.purchase_id','=','purchases.id')
->whereNull('payments.deleted_at')
->groupBy('purchases.id')->get();
When I run the code below the 1st result is not included.
Result
id | name | total
2 | Recipe Book 60
3 | EngineX Book 0
I know why It is not included but the problem is if I remove whereNull('payments.deleted_at') that particular row in payments
will also add to the sum.How should I solve this ??
Expected Result
id | name | total
1 | Gamerzone Book 0
2 | Recipe Book 60
3 | EngineX Book 0
In this case your join condition should looks like this:
ON (payments.booking_id = purchases.id AND payments.deleted_at IS NOT NULL)
And it is not about WHERE (according to your SELECT).
You should use join-closure like this:
$query = DB::table('purchases')
->select(['purchases.*', DB::raw("IFNULL(sum(payments.amount),0) as total")])
->leftJoin('payments', function($join) {
$join->on('payments.booking_id', '=', 'purchases.id');
$join->on('payments.deleted_at', 'IS', DB::raw('NOT NULL'));
})
->groupBy('purchases.id')->get();
Just replace
->leftJoin('payments','payments.booking_id','=','purchases.id')
with
->leftJoin('payments', function($join) {
$join->on('payments.booking_id', '=', 'purchases.id');
$join->on('payments.deleted_at', 'IS', DB::raw('NOT NULL'));
})
and remove this:
->whereNull('payments.deleted_at')
it should help.