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.
Related
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();
}
}
I read most of the solutions here with similar questions and it did not solve my problem and I cannot find anything online that can help me.
I am trying to make query on condition where user_id = session user_id but I get error when I make INNER join
ambiguous column name
for this
public List<CartModelClass>getCarts1(){
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = { "ID" , "user_id", "food_id", "quantity", "price", "origin", "destination","description","company_name","search_id"};
String sqltable2 = "OrderDetails LEFT JOIN OrderDetails WHERE user_id LIKE '%%' ";
qb.setTables(sqltable2);
Cursor c = qb.query(db,sqlSelect, null, null ,null ,null ,null);
final List<CartModelClass> result = new ArrayList<>();
if (c.moveToFirst()) {
do {
result.add(new CartModelClass(
c.getString(c.getColumnIndex("user_id")),
c.getString(c.getColumnIndex("food_id")),
c.getString(c.getColumnIndex("quantity")),
c.getString(c.getColumnIndex("price")),
c.getString(c.getColumnIndex("origin")),
c.getString(c.getColumnIndex("destination")),
c.getString(c.getColumnIndex("description")),
c.getString(c.getColumnIndex("company_name")),
c.getString(c.getColumnIndex("search_id"))
));
} while (c.moveToNext());
}
return result;
}
so I changed InnerJoin and made it just table where user_id like"%%" but I only get the last user_id who added to cart and show all data for all users
I want to show only added cart for user_id = session user_id so i can use it in here
loadListFood
private void loadListFood(){
sessionManager= new SessionManager(getActivity());
final Hashmap<String, String> user = sessionManager.getUserDetail();
user.get(USER_ID);
listdata = new Database(this.getContext.getCarts1());
for(CartModelClass order : listdata)
user_id = order.getUser_id
if(user.get(USER_ID).equals(user_id)){
listdata = new Database(this.getContext()).getCarts();
adapter = new CartAdapter(listdata, this.getContext());
recyclerView.setAdapter(adapter);
int total = 0;
for (CartModelClass order : listdata) {
total += (Integer.parseInt(order.getPrice())) * (Integer.parseInt(order.getQuantity()));
Locale locale = new Locale("en", "US");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
txtTotalPrice.setText(fmt.format(total));
}
}else {
Toast.makeText(getContext(), "No Cart Added", Toast.LENGTH_LONG).show();
}
}
You are self joining the table OrderDetails.
In this case you must set aliases to both copies of the table, like:
OrderDetails as o1 LEFT JOIN OrderDetails as o2 ...
Now in the ON clause you must qualify the column names properly, like:
ON o1.user_id = o2.something
If you don't, you get that error message, because the column name user_id could belong to either of the 2 copies of the table.
Also:
What is session user_id? Is it a column name?
If it is then the problem is that it contains a space in its name.
Enclose it in square brackets, so the statemnet should be:
OrderDetails as o1 LEFT JOIN OrderDetails as o2
ON o1.user_id = o2.[session user_id]
I have 2 linq queries. First query does nothing because of unique index and this is OK. But second also does nothing while it should add records . If I bypass first query second query works. Should I refresh entity ? How ?
foreach (var product in productList)
{
cc2nexo_SubiektProduct newproduct = new cc2nexo_SubiektProduct();
newproduct.Name = product.Name;
newproduct.VAT = product.VAT;
newproduct.Id = product.Id;
foreach (var stawkaVAT in myNexo_ExitoEntities.StawkiVat)
{
if (stawkaVAT.Stawka * 100 == tryconvert_dec(newproduct.VAT))
{
newproduct.VAT_Id = stawkaVAT.Id;
}
}
myNexo_ExitoEntities.cc2nexo_SubiektProduct.Add(newproduct);
SurroundWithTryCatchDB(() =>
{
myNexo_ExitoEntities.SaveChanges();
});
}
var orders = (from myorders in myNexo_ExitoEntities.temp_SubiektOrderList
select myorders).ToList();
foreach (var order in orders)
{
cc2nexo_SubiektOrderList neworder = new cc2nexo_SubiektOrderList();
neworder.Data_utworzenia_sprawy = tryconvert_date(order.Data_utworzenia_sprawy);
neworder.Data_modyfikacji_sprawy = tryconvert_date(order.Data_modyfikacji_sprawy);
neworder.Data_umowy = tryconvert_date(order.Data_umowy);
neworder.Id = order.Id;
myNexo_ExitoEntities.cc2nexo_SubiektOrderList.Add(neworder);
SurroundWithTryCatchDB(() =>
{
myNexo_ExitoEntities.SaveChanges();
});
Debug.WriteLine(neworder.LastName);
}
I am receiving an error
Cannot insert duplicate key row in object 'dbo.cc2nexo_SubiektProduct' with unique index 'K_ID'. The duplicate key value is (1).The statement has been terminated
The reason of problem was SurroundWithTryCatchDB procedure not listed in my question. Because first query caused exception due to unique index all next SaveChanges did not work. I have changed my first query to work with unique values and now everything is OK.
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.
I have below a collection of rows and each row consists of productid, unitid, countryid.
I need to find the details for each row in the corresponding tables (products, units, country)
for product - select product name, updatedby
for unitid - select unit name , updatedby
for countryid - select countryname, uploadby
and returning the rows which has the same format
Id = product id or unitid or countryid
name = proudct name or unit name or countryname
modified = product updatedby or unit updated by or country uploadby
So, in summary -
1. For a Collection of rows
a. use the id to get the extra details from the respective table
b. return the same type of collection for the results
2. do step 1 for
2.a For RegularToys (Run this logic on TableBigA)
2.b For CustomToys(Run this logic on TableB)
3. Return all the rows
by adding 2.a and 2.b
How to write an sql/linq query for this? thanks
If I'm understanding correctly, you want to use a given ID to find either a product, a unit or a country but you're not sure which. If that's the case, then you can build out deferred queries like this to find the given entity:
var prod = from p in db.Products
where p.ProductId = id
select new { Id = p.ProductId, Name = p.ProductName, Modified = p.UpdatedBy };
var unit = from u in db.Units
where p.UnitId = id
select new { Id = u.UnitId, Name = u.UnitName, Modified = p.UpdatedBy };
var ctry = from c in db.Countries
where c.CountryId = id
select new { Id = c.CountryId, Name = c.CountryName, Modified = c.UploadBy };
And then execute the queries until you find an entity that matches (with ?? being the null-coalesce operator that returns the right value if the left result is null).
var res = prod.SingleOrDefault() ??
unit.SingleOrDefault() ??
ctry.SingleOrDefault() ??
new { Id = id, Name = null, Modifed = null };
Without any further details I can't be more specific about the condition below, but I think you are asking for something along these lines. I'm assuming your Id's are int's (but this can be easily changed if not) and you already have an Entity Data Model for the tables you describe.
Create a class for your common data:
class RowDetail
{
public int Id { get; set; }
public string Name { get; set; }
public string Modified { get; set; }
}
Pull the information out of each of the sub tables into a new record:
IEnumerable<RowDetail> products =
from p in db.Products
where <<CONDITION>>
select
new RowDetail()
{
Id = p.ProductId,
Name = p.ProductName,
Modified = p.UpdatedBy
};
IEnumerable<RowDetail> units =
from u in db.Units
where <<CONDITION>>
select
new RowDetail()
{
Id = u.UnitId,
Name = u.UnitName,
Modified = u.UpdatedBy
};
IEnumerable<RowDetail> countries =
from c in db.Countries
where <<CONDITION>>
select
new RowDetail()
{
Id = c.CountryId,
Name = c.CountryName,
Modified = c.UploadBy
};
Finally pull all the records together in a single collection:
IEnumerable<RowDetail> results = products.Union(units).Union(countries);
I'm not sure if this is exactly what you are looking for, so feel free to give feedback and/or more details if further assistance is required.