I have an E-commerce website, I want to sort the products in product page by in-stock first so I did this and it works just fine:
$products = Product::orderByDesc('quantity')->get();
Now, I added a new column to the product table which is product_order that will take an integer so that I can custom sort the products, I tried the following code:
$products = Product::orderByDesc('quantity')->orderByDesc('product_order')->get();
The problem is that it only sorts them by quantity, the second orderByDesc is not effective, how can I make it effective?
I managed to solve the issue by doing the following:
$productsQty = Product::orderByDesc('product_order');
$products = $productsQty->orderByDesc('quantity')->get();
foreach ($products as $product) {
if($product->quantity <= 0) {
$product->product_order = 0;
$product->save();
}
}
Related
I am creating Order including OrderDetail. When I have a Cart consisting of many Products, I create an Order, I want each product ID to be added to the OrderDetail including the OrderID.
But currently, I only get a ProductID (OrderID) in the first loop added to the OrderDetail. When I debug, the loop still executes enough times quantity of Product in Cart but is not added to OrderDetail.
So what is the problem that I am facing here?
Repository
public bool CreateOrder(CartViewModel invoiceVM, string userId)
{
invoiceVM.Invoices.CreateAt = DateTime.Now;
_dbContext.Invoice.Add(invoiceVM.Invoices);
_dbContext.SaveChanges();
decimal orderTotal = 0;
var cartItems = GetCartItem(userId);
foreach (var item in cartItems)
{
var invoiceDetail = new InvoiceDetails
{
ProductId = item.Products.Id,
InvoiceId = invoiceVM.Invoices.Id,
Price = item.Products.Price * item.Quantity,
Quantity = item.Quantity,
};
orderTotal += (item.Quantity * item.Products.Price);
_dbContext.InvoiceDetails.Add(invoiceDetail);
}
invoiceVM.Invoices.OrderTotal = orderTotal;
_dbContext.SaveChanges();
return true;
}
"but is not added to OrderDetail" You mean that the Order is created in your database, But you can't see any OrderDetail in your database ?
if
_dbContext.InvoiceDetails.Add(invoiceDetail);
.
.
_dbContext.SaveChanges();
are successfully pass with no errors, It save data in your database and I think it's your CartViewModel that is not updating.
you can add your data to CartViewModel in you loop or run another GetInvoice() from your dbContext.
I've two tables products, stock I want to select all rows from table products that not inserted on stock and i've 2 conditions
1: column products.s_compnay_id = users.u_company_id
2: cloumn stock.s_company_id =users.u_company_id
that's my model
<?php
Class UserProducts_m extends CI_Model{
function index(){
$session_data = $this->session->userdata('logged_in');
$name = $session_data['username'];
$this->db->select('u_company_id');
$this->db->from('users');
$this->db->where('u_username', $name);
$user_data = $query = $this->db->get();
if ($user_data->num_rows() > 0) {
foreach ($query->result_array() as $row_userdata) {
$usercompanyid[] = $row_userdata;
}
$usercompany=$usercompanyid[0]['u_company_id'];
}
$query="select products.* from products where !FIND_IN_SET(products.p_id,select stock.s_p_id from stock and stock.s_company_id=$usercompany and p_company_id=$usercompany)";
$this->db->query($query);
$result= $this->db->get();
if ($result->num_rows() > 0) {
foreach ($result->result_array() as $row_result) {
$product_data[] = $row_result;
}
}
//return $result=$query->result();
}
}
?>
And that's my controller
<?php
Class UserProducts extends CI_Controller {
function index(){
$this->load->model("UserProducts_m");
$this->load->model("user");
$this->load->view("userproducts_v",array(
'userdata'=>$this->user->userdata(),
'userproducts'=>$this->UserProducts_m->index()
));
}
}
?>
that's my errors
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'select stock.s_p_id from stock and stock.s_company_id=1 and p_company_id=1)' at line 1
select products.* from products where !FIND_IN_SET(products.p_id,select stock.s_p_id from stock and stock.s_company_id=1 and p_company_id=1)
Filename: C:/xampp/htdocs/Elvan/system/database/DB_driver.php
Line Number: 691
I suggest you try putting curly braces around the vars in your query statement. Then it should resolve to array values properly.
$query="select products.* from products where
!find_in_set(products.p_id,select stock.s_p_id from stock and
stock.s_company_id = {$usercompanyid[0]['u_company_id']} and
p_company_id = {$usercompanyid[0]['u_company_id']})";
I see a couple other problems.
The line
$result= $this->db->get();
is not needed because $this->db->query($query); already returned a database result object. Do this
$result = $this->db->query($query);
if ($result->num_rows() > 0)
{ ...
Then you have this useless block of code (Pardon me for being blunt)
foreach ($result->result_array() as $row_result)
{
$product_data[] = $row_result;
}
This is useless because your code just copies array values from one array to another. You'll save a lot of code execution with the following which produces the same thing your foreach loop does.
$product_data = $result->result_array();
result->array() returns an array where each item is an array representing a table row.
You did the same thing earlier adding items to the $usercompanyid array. Do this.
if ($user_data->num_rows() > 0)
{
$usercompanyid = $query->result_array();
}
One last problem. It appears that UserProducts_m::index() does not return anything.
You can use the NOT IN sql query for this.
SELECT *
FROM products
WHERE product_id NOT IN (select field name form stock where clause);
I am using a module that displays new added products in home page. I need to customize the module so that this list doesnt contain products sold. In other words, if a product is out of stock before the number of days it is condidered new is over, then do not show this product in list.
I can do it in view part by using {if $product.quantity < 0}{/if} but my goal is to perform it in controller. Here is my code:
function hookHome($params)
{
global $smarty, $cookie;
$nb = intval(Configuration::get('HOME_NEW_PRODUCTS_NBR'));
$rand = intval(Configuration::get('HOME_NEW_PRODUCTS_RANDOM'));
if ($rand == 1) {
$products = Product::getNewProducts(intval($cookie->id_lang), 0, $nb);
if ( $products )
{
shuffle($products);
array_slice($products, ($nb ? $nb : 10));
}
}
else
{
$products = Product::getNewProducts(intval($cookie->id_lang), NULL - 0, (intval($nb ? $nb : 4)), false, NULL, NULL);
}
$smarty->assign(array(
....
'products' => $products,
....
);
return $this->display(__FILE__, 'homenewproducts.tpl');
}
How can I override the class Product so that the method getNewProducts take into account excluding products out of stock?
Or at least, how can I remove from $products the products with quantity =0 using PHP?
Your help is appreciated.
Well, the solution I am using now is:
In product.php, I changed the sql queries in getNewProducts method inside of NewProductsController so that it takes into account if product is available in stock
I added AND 'quantity'!=0 in line 2062 and $sql->where('p.'quantity' != 0'); in line 2086 . Prestashop 1.6.0.6.
Of course, better override the classe Product.php than modifying it.
I hope it can help.
I have a SQLite query to pull orders from an ORDERS table in a database:
qry.executeSql("SELECT o.ID AS orderIDx, o.token AS orderTokenx, r.retailerName AS retailerNamex FROM orders AS o LEFT JOIN retailers AS r ON r.token = o.retailerID ", [], function(tx, results){
//query was a success
var len = results.rows.length;
for (var i=0; i<len; i++){
var orderID = results.rows.item(i).orderIDx;
var orderToken = results.rows.item(i).orderTokenx;
var retailerName = results.rows.item(i).retailerNamex;
//create container for order and populate it with orderItems in the below query
qry.executeSql("SELECT * FROM orderItems WHERE orderID = '"+orderToken+"' ", [], function(tx1, results1){
var len1 = results1.rows.length;
for (var i1=0; i1<len1; i1++){
$('.orderItem.'+orderID+' p').append(results1.rows.item(i1).productName);
}
});
}
});
This is my query but with a lot of clutter taken out, ive left the essentials.
So I am trying to loop through the orders table and show order specific info in one section, and within that as a drop down I widh to displat each order item. So within the order loop I am using that ID to call orderItems etc... but it is only appending the results of the orderItem query in the last container.
I hink this is because the query is Asynchronous, but I am unsure how to popupulate the orderItem container before the next loop for the order query is carried out :/
I am struggling to do the same thing with Asynchronmous jQuery AJAX stuff.. so if this is linked then an explanation would be great.
Also, I was going to use a JOIN to join the order and orerItems tables in the outer query, but was then unsure about how to loop through the items as well as the orders within 1 loop?
To me the problem seems to be the orderID variable which changes before the orderItems get appended.
I think it will help if you would change last for loop into
var len1 = results1.rows.length;
var order_id = results1.rows.item(0).orderID;
for (var i1=0; i1<len1; i1++){
$('.orderItem.'+order_id+' p').append(results1.rows.item(i1).productName);
}
In this case you won't be using the changed variable anymore.
In my theme development, I don't find the way to get all the products of my shop.
Although, I can retrieve all the collections with the variable collections (exemple: {% for c in collections %}).
Check this url: https://help.shopify.com/en/themes/customization/collections/change-catalog-page
Like magic... all your products...
Get all products at once or to run a query(API Request) for all products in shopify store :
using this app is more managed -> https://github.com/phpish/shopify_private_app-skeleton so, my solution below is based on this app or you can relate the solution with your solution as well
<?php
session_start();
require __DIR__.'/vendor/autoload.php';
use phpish\shopify;
require __DIR__.'/conf.php';
$shopify = shopify\client(SHOPIFY_SHOP, SHOPIFY_APP_API_KEY, SHOPIFY_APP_PASSWORD, true);
try
{
$products = $shopify('GET /admin/products/count.json', array('published_status'=>'published'));
$totalproducts = $shopify('GET /admin/products/count.json', array('published_status'=>'published'));
$limit = 50;
$totalpage = ceil($totalproducts/$limit);
for($i=1; $i<=$totalpage; $i++){
$products = $shopify('GET /admin/products.json?'.$limit.'=50&page='.$i, array('published_status'=>'published'));
foreach($products as $product){
//do anything at once for all the products in store
}
}
}
catch (shopify\ApiException $e)
{
//
}
Summary : The idea is to retrieve with page=x as parameter. after calculating the number of pages we will have with specified limit i.e 50 at one time fetch.