we want search data from sales table where , payment_status is pending . i try -
$this->datatables
->select("id, date, reference_no, biller, customer, sale_status")
->from('sales')
->where('due_date <=', date('Y-m-d'))
->where('payment_status =', 'pending')
it work good , but when we want search both value of payment_status , pending & partial at same time it not work. i try this code-
$this->datatables
->select("id, date, reference_no, biller, customer, sale_status, grand_total, paid, (grand_total-paid) as balance, payment_status")
->from('sales')
->where('due_date <=', date('Y-m-d'))
->where('payment_status =', 'pending')
->where('payment_status =', 'partial');
Use or_where
$this->datatables
->select("id, date, reference_no, biller, customer, sale_status, grand_total, paid, (grand_total-paid) as balance, payment_status")
->from('sales')
->where('due_date <=', date('Y-m-d'))
->where('payment_status =', 'pending')
->or_where('payment_status =', 'partial');
It make you condition where (payment_status ='pending' OR payment_status ='partial' )
Related
I'm trying to display a data by month and displays the product with the highest value or bought quantity. But I don't know how I should do it.
This is the code I have and tried so far
public function viewSales(){
$data = sales::select(
[sales::raw("SUM(product_fee) as product_fee, MONTHNAME(created_at) as month_name, MAX(bought) as bought"),'product']
)->whereYear('created_at', date("Y"))
->orderBy('created_at', 'asc')
->groupBy('month_name')
->get();
return view('admin.viewSales', compact('data'));
}
This is what's inside my database
id
product
bought
product_fee
created_at
1
Dictionary
1
200
2023-01-14 18:55:34
2
Horror
3
100
2023-01-15 17:55:34
3
How to cook
5
300
2023-01-16 11:55:34
and this is what I'm trying to display
Most bought product
sold
overall earning
How to cook
5
600
i think you can try this :
public function viewSales(){
$data = sales::select(
[sales::raw("(bought*product_fee) as overall_earning, MONTHNAME(created_at) as month_name, MAX(bought) as bought"),'product']
)->whereYear('created_at', date("Y"))
->orderBy('created_at', 'asc')
->groupBy('month_name')
->get();
return view('admin.viewSales', compact('data'));
}
I hope this works for you
Below SQL will give you the desired output for current year and month.
Fetch for current year
SELECT
product as most_bought_product_for_the_year,
bought as sold,
(SELECT SUM(product_fee) from products WHERE YEAR(created_at) = year(curdate())) as overall_earning
FROM `products`
WHERE
bought = (SELECT MAX(bought) from products WHERE YEAR(created_at) = year(curdate()));
Fetch for months of the current year
SELECT
product as most_bought_for_the_month,
bought as sold,
MONTHNAME(created_at) as month_name,
SUM(product_fee) as overall_earning
FROM `products`
WHERE
YEAR(created_at) = YEAR(curdate())
AND
bought IN (SELECT MAX(bought) from products WHERE YEAR(created_at) = YEAR(curdate()) GROUP by MONTH(created_at))
GROUP BY MONTH(created_at)
ORDER BY MONTH(created_at);
SQL Fiddle
i has raw query in laravel like this
public function getPopularBook(){
$book = DB::select("
with totalReview as(
SELECT r.book_id , count(r.id)
FROM review r
GROUP BY r.book_id
)
SELECT *
from totalReview x
left JOIN (
SELECT b.*,
case when ((now() >= d.discount_start_date and now() <= d.discount_end_date) or (now() >= d.discount_start_date and d.discount_end_date is null)) then (b.book_price-d.discount_price)
ELSE b.book_price
end as final_price
FROM discount d
right JOIN book b
on d.book_id = b.id
) as y
on x.book_id = y.id
ORDER BY x.count DESC, y.final_price ASC
LIMIT 8"
);
return $book;
}
so when i want to return a paginate, it doesn't work so can i convert this to query build to use paginate
This is a very un-optimized raw query in itself. You are performing too many Join in Subquery just to sort by price
i'm assuming the database table:
books[ id, name, price ]
reviews[ id, book_id ]
discounts[ id, book_id, start_date, end_date, discount_price]
Look how easy it is if you just use Eloquent:
Book::withCount('reviews')->orderBy('reviews_count')->get();
this will give you all the Books order by number of reviews
now with the final price, this can be a bit tricky, let's take a look at a query when we don't consider discount time
Book::withCount('reviews')
->withSum('discounts', 'discount_price') //i'm assuming a book can have many discount at the same time, so i just sum them all
->addSelect(
DB::raw('final_price AS (books.price - discounts_sum_discount_price)')
)
->orderBy('reviews_count', 'asc') // =you can specify ascending or descending
->orderBy('final_price', 'desc') //in laravel chaining multiple orderBy to order multiple column
->get();
I dont even need to use Subquery!! But how do we actually only add the "active" discount?, just need to modify the withSum a bit:
Book::withCount('reviews')
->withSum(
[
'discounts' => function($query) {
$query->where('start_date', '<=', Carbon::now())
->where('end_date', '>=', Carbon::now())
}
],
'discount_price'
)
->addSelect(
DB::raw('final_price AS (books.price - discounts_sum_discount_price)')
)
->orderBy('reviews_count', 'asc') // =you can specify ascending or descending
->orderBy('final_price', 'desc') //in laravel chaining multiple orderBy to order multiple column
->get();
and it is done
What about pagination? just replace the get() method with paginate():
Book::withCount('reviews')
->withSum(['discounts' => function($query) {
$query->where('start_date', '<=', Carbon::now())->where('end_date', '>=', Carbon::now())
}],'discount_price')
->addSelect(DB::raw('final_price AS (books.price - discounts_sum_discount_price)')) //just format to be a bit cleaner, nothing had changed
->orderBy('reviews_count', 'asc')
->orderBy('final_price', 'desc')
->paginate(10); //10 books per page
WARNING: this is written with ELoquent ORM, not QueryBuilder, so you must define your relationship first
my sqlfiddle eample
Hello there,
according to the above sqlfiddle example;
I have a table A where the products are listed and a table B with different prices for different periods associated with these products.
Here I show these prices according to the date the user has chosen. There is no problem.
However, if the user has not selected a date, I cannot show the price of the period closest to today by default.
In the example I gave, the sql query does this successfully, but I cannot write it successfully in the form of laravel query. Or as an Eloquent orm query
How can I do that?
$query->select(['tableA.*', 'tableB.start_date', 'tableB.end_date', 'tableB.price'])
->join('tableB', function($join) {
$join->on('tableA.id', '=', 'tableB.pro_id');
})->where(function($sq) use ($postFrom) {
$sq->when($postFrom[0]=='0', function ($syq) {
$syq->whereRaw('DAYOFYEAR(curdate()) <= DAYOFYEAR(tableB.end_date)');
}, function ($stq) use ($postFrom) {
$stq->whereDate('tableB.start_date', '<=', $postFrom[0])
->whereDate('tableB.end_date', '>=', $postFrom[0]);
});
})->orWhere(function($ssq) use ($postTo) {
$ssq->whereDate('tableB.start_date', '<=', $postTo[0])
->whereDate('tableB.end_date', '>=', $postTo[0]);
})->groupBy('tableA.id')->orderBy('tableB.price', $sortDirection);
note1: $postFrom and $postTo are the start and end dates from the user. If the user did not submit a date, $postFrom is displayed as 0.
note2: I show the default price when the $postFrom[0] == '0' condition is met.
note3: The '2021-03-07' value in the sqlfiddle example is used for example instead of the dynamic present value.
note4: According to this query, it takes the price value of the first period as default. But that's not what I want.
note5: I can't use 'joinSub' because Laravel version is 5.5.
note6:In the example I want to convert to Laravel Query form, the sql query that works without any problems:
select `tableA`.*, `tableB`.`start_date`, `tableB`.`end_date`, `tableB`.`price`
from `tableA`
right join(
SELECT id, start_date, end_date, pro_id, price, DATEDIFF(`tableB`.`end_date`, '2021-03-07') diff
FROM `tableB` GROUP BY id order by diff asc
) `tableB` on `tableA`.`id` = `tableB`.`pro_id` where (date(`end_date`) >= '2021-03-07')
group by `tableA`.`id` order by `price` desc
This is an equivalent query of your query. I haven't executed.
If Laravel Version is greater then 5.5
$query1 = DB::table('tableB')
->selectRaw("id, start_date, end_date, pro_id, price, DATEDIFF(end_date, '2021-03-07') AS diff")
->groupBy('id')->orderBy('diff','ASC');
TableA::select('tableA.*', 'tableB.start_date', 'tableB.end_date', 'tableB.price')
->joinSub($query1, 'tableB', function ($join)
{
$join->on('tableA.id', '=', 'tableB.pro_id');
})
->whereDate('tableB.end_date','>=','2021-03-07')
->groupBy('tableA.id')->orderBy('price','DESC')->get();
For Laravel 5.5
TableA::select('tableA.*', 'tableB.start_date', 'tableB.end_date', 'tableB.price')
->join(DB::raw("(SELECT id, start_date, end_date, pro_id, price,
DATEDIFF(`tableB`.`end_date`, '2021-03-07') diff
FROM `tableB` GROUP BY id order by diff asc) table2 "), function ($join)
{
$join->on('tableA.id', '=', 'table2.pro_id');
})
->whereDate('table2.end_date','>=','2021-03-07')
->groupBy('tableA.id')->orderBy('price','DESC')->get();
I want to get most view by query:
$this->db->select("a.pid, a.title, a.pic, a.date_created, d.view as post_view");
$this->db->from("posts as a");
$this->db->join('views as d', 'd.post_id=a.pid');
$this->db->join('cats as b', 'b.catid=a.catid'); //ensure Cat existed
$this->db->where("a.block", 0);
$this->db->order_by("d.view", "desc");
$this->db->limit(5);
$query = $this->db->get();
return $query->result();
but always automatically add order_by pid asc. and never order desc for d.view field. i try to print query string and here:
SELECT `a`.`pid`, `a`.`title`, `a`.`pic`, `a`.`date_created`, `d`.`view` as `post_view` FROM `posts` as `a` JOIN `views` as `d` ON `d`.`post_id`=`a`.`pid` JOIN `cats` as `b` ON `b`.`catid`=`a`.`catid` WHERE `a`.`block` =0 ORDER BY `pid` asc, `d`.`view` DESC LIMIT 5
Any suggestion to fix? (CI version 3.*)
Does anyone know where I can start trying to get at cart information from unregistered users. I want to be able to look at abandon carts from people who are not logged in. This doesn't seem to be a default function of magento, but I have a feeling it's in the db somewhere.
all quotes are stored in sales_flat_quote table
I have checked this query and find one or two cases where some results are missing in the results but shows on the magento abandoned cart report. Here is what I tried.
SELECT entity_id, customer_firstname, customer_email, items_count, grand_total, created_at
FROM sales_flat_quote
WHERE entity_id NOT IN (SELECT quote_item_id AS quote_id FROM sales_flat_order_item)
AND items_count >0
AND customer_email IS NOT NULL
ORDER BY `sales_flat_quote`.`created_at` DESC
In case anyone is interested, this is the sql query that I came up with for getting abandon cart items directly out of the database. You'll need to change the date
SELECT quote_id, sku, qty, price, custom_price, row_total, created_at, product_id, store_id
FROM mage_sales_flat_quote_item
WHERE created_at > "2011-04-01"
AND quote_id NOT IN (SELECT quote_item_id AS quote_id FROM mage_sales_flat_order_item)
AND store_id IS NOT NULL
This is more like it.
SELECT `main_table`.*, GROUP_CONCAT(item.sku) AS `skus`, (main_table.base_subtotal_with_discount*main_table.base_to_global_rate) AS `subtotal`, `cust_email`.`email`, `cust_fname`.`value` AS `firstname`, `cust_lname`.`value` AS `lastname`, CONCAT_WS(' ', cust_fname.value, cust_lname.value) AS `customer_name` FROM `sales_flat_quote` AS `main_table`
INNER JOIN `sales_flat_quote_item` AS `item` ON item.quote_id = main_table.entity_id
INNER JOIN `customer_entity` AS `cust_email` ON cust_email.entity_id = main_table.customer_id
INNER JOIN `customer_entity_varchar` AS `cust_fname` ON cust_fname.entity_id = main_table.customer_id AND cust_fname.attribute_id = 5
INNER JOIN `customer_entity_varchar` AS `cust_lname` ON cust_lname.entity_id = main_table.customer_id AND cust_lname.attribute_id = 7 WHERE (items_count != '0') AND (main_table.is_active = '1') AND (main_table.created_at >= '2013-02-04 00:00:00' AND main_table.created_at <= '2013-02-04 24:00:00') AND (main_table.updated_at >= '2013-02-04 00:00:00' AND main_table.updated_at <= '2013-02-04 24:00:00') GROUP BY `item`.`quote_id` ORDER BY updated_at DESC