MVC update the database based on a non primary key value - sql

I have a database table that looks like this:
My goal is to update my "unavail" table based on the ID of either the component, part, or item depending on which one is relevant in my situation.
For example, if the partID = 43 I want to add to the 'unavail' column
I first started working on this by trying this
db.OffSiteItemDetails.Find(sod.PartID).unavail += sod.comp_returned;
(Where sod.PartId = 43)
But I quickly realized it was just checking for where the "ID" was equal to 43 which isn't what I want. After some investigation I saw people suggesting using
db.Where(x => x.non-pk == value)
So I created this
db.OffSiteItemDetails.Where(x => x.componentID == sod.ComponentID);
But from here I don't know how to change my unavail table values.
This was a tough question to type so if you need more clarity just ask

foreach(var item in db.OffSiteItemDetails.Where(x => x.componentID == sod.ComponentID))
{
// item.unavail = [new value]
// db.Update(item);
// ...I don't know how you update the data in your database
}
Something like that?

Related

How to modify value in column typeorm

I have 2 tables contractPoint and contractPointHistory
ContractPointHistory
ContractPoint
I would like to get contractPoint where point will be subtracted by pointChange. For example: ContractPoint -> id: 3, point: 5
ContractPointHistory has contractPointId: 3 and pointChange: -5. So after manipulating point in contractPoint should be 0
I wrote this code, but it works just for getRawMany(), not for getMany()
const contractPoints = await getRepository(ContractPoint).createQueryBuilder('contractPoint')
.addSelect('"contractPoint".point + COALESCE((SELECT SUM(cpHistory.point_change) FROM contract_point_history AS cpHistory WHERE cpHistory.contract_point_id = contractPoint.id), 0) AS points')
.andWhere('EXTRACT(YEAR FROM contractPoint.validFrom) = :year', { year })
.andWhere('contractPoint.contractId = :contractId', { contractId })
.orderBy('contractPoint.grantedAt', OrderByDirection.Desc)
.getMany();
The method getMany can be used to select all attributes of an entity. However, if one wants to select some specific attributes of an entity then one needs to use getRawMany.
As per the documentation -
There are two types of results you can get using select query builder:
entities or raw results. Most of the time, you need to select real
entities from your database, for example, users. For this purpose, you
use getOne and getMany. But sometimes you need to select some specific
data, let's say the sum of all user photos. This data is not an
entity, it's called raw data. To get raw data, you use getRawOne and
getRawMany
From this, we can conclude that the query which you want to generate can not be made using getMany method.

How to change a field value in EF Core Select

Imagine that an entity has many fields and I just want to make changes in 1-2 fields, Is it possible to do that in Select? I don't want to mention all fields in my Select cause.
Ex: I want to return all fields and make a tiny change in OrderId field at the same time.
_context.Set<Table>.Select(t=>t.OrderId=t.OrderId+1)
A workaround I've found is to use select and copy every field to a new instance of your entity/object and change the field you want a computed value for, like:
_context.Operations
.Where(t => t.SessionId == sessionId)
.Select(o => new Operation
{
OperationId = o.OperationId + 1;
SessionId = o.SessionId,
Amount = o.Amount,
Date = o.Date,
});

play-slick scala many to many

I have an endpoint lets say /order/ where i can send json object(my order), which contains some products etc, so my problem is i have to first save the order and wait for the order id back from the db and then save my products with this new order id( we are talking many to many relation thats why theres another table)
Consider this controller method
def postOrder = Action(parse.json[OrderRest]) { req => {
Created(Json.toJson(manageOrderService.insertOrder(req.body)))
}
}
this is how my repo methods look like
def addOrder(order: Order) = db.run {
(orders returning orders) += order
}
how can i chain db.runs to first insert order, get order id and then insert my products with this order id i just got?
im thinking about putting some service between my controller and repo, and managing those actions there, but i have no idea where to start
You can use for to chain database operations. Here is an example of adding a table to a db by adding a header row to represent the table and then adding the data rows. In this case it is a simple table containing (age, value).
/** Add a new table to the database */
def addTable(name: String, table: Seq[(Int, Int)]) = {
val action = for {
key <- (Headers returning Headers.map(_.tableId)) += HeadersRow(0, name)
_ <- Values ++= table.map { case (age, value) => ValuesRow(key, age, value) }
} yield key
db.run(action.transactionally)
}
This is cut down from the working code, but it should give the idea of how to do what you want. The first for statement would generate the order id and then the second statement would add the order with that order id.
This is done transactionally so that the new order will not be created unless the order data is valid (in database terms).

Find a records containg a specific tag

I have a following DB schema:
User
- id
- name (String)
UserTag
- user_id
- tag_id
Tag
- id
- key (String)
And i also have a pretty complex users-search chain with a lot of where statements. I'm trying to figure out how to include one another where condition to my chain - filtering for users that has a specific tag assigned (ID of this tag is unknown, just it's key is known).
So, here is more or less how my code looks:
col = User.all
col = col.where('cats_count <= 0') if args[:no_cat]
col = col.where('dogs_count <= 0') if args[:no_dog]
col = col.where('other_pets_count <= 0') if args[:no_other_pet]
# ... tag logic filtering here ...
col = col.where('age > 100') if args[:old]
And i want to filter for a users, who has a Tag with key=non_smoking assigned. Ideally, i would love it to be database-engine independen, if that's important - i'm on sqlite/postgres.
Honestly i have completely no any ideas on how to deal with that, i probably lack some knowledge in SQL matter and then, in Rails/ActiveRecord.
You can specify joins and the put conditions on the joined tables. So maybe something like (untested, off the top of my head)
col.joins(user_tags: :tag).where(user_tags: { tag: { key: 'non_smoking' } })

Magento: Get Collection of Order Items for a product collection filtered by an attribute

I'm working on developing a category roll-up report for a Magento (1.6) store.
To that end, I want to get an Order Item collection for a subset of products - those product whose unique category id (that's a Magento product attribute that I created) match a particular value.
I can get the relevant result set by basing the collection on catalog/product.
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('unique_category_id', '75')
->joinTable('sales/order_item', 'product_id=entity_id', array('price'=>'price','qty_ordered' => 'qty_ordered'));
Magento doesn't like it, since there are duplicate entries for the same product id.
How do I craft the code to get this result set based on Order Items? Joining in the product collection filtered by an attribute is eluding me. This code isn't doing the trick, since it assumes that attribute is on the Order Item, and not the Product.
$collection = Mage::getModel('sales/order_item')
->getCollection()
->join('catalog/product', 'entity_id=product_id')
->addAttributeToFilter('unique_category_id', '75');
Any help is appreciated.
The only way to make cross entity selects work cleanly and efficiently is by building the SQL with the collections select object.
$attributeCode = 'unique_category_id';
$alias = $attributeCode.'_table';
$attribute = Mage::getSingleton('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attributeCode);
$collection = Mage::getResourceModel('sales/order_item_collection');
$select = $collection->getSelect()->join(
array($alias => $attribute->getBackendTable()),
"main_table.product_id = $alias.entity_id AND $alias.attribute_id={$attribute->getId()}",
array($attributeCode => 'value')
)
->where("$alias.value=?", 75);
This works quite well for me. I tend to skip going the full way of joining the eav_entity_type table, then eav_attribute, then the value table etc for performance reasons. Since the attribute_id is entity specific, that is all that is needed.
Depending on the scope of your attribute you might need to add in the store id, too.