Update another table row in Azure Mobile Services Javascript - azure-mobile-services

I have two tables in Azure Mobile Services (javascript backend): TableA and TableB. I want to update a specific row in TableB everytime a read query runs in TableA. Both tables have the same column "Date" used to identify which row to update.
I'm trying to accomplish that through the following code (added to the read script in TableA), which is not working to update TableB (it works to update TableA, if I change table name in var myTable to TableA)
function read(query, user, request) {
request.execute({ success: function(results)
{
request.respond();
//retrieve TableB reference
var myTable = tables.getTable('TableB');
myTable.where({
//retrieve TableB specific row by date
Date: results[0].Date
}).read({
success: function(results){
//reference row to be updated in TableB
var tableRef = results[0];
tableRef.Views = tableRef.Views + 1;
//update row in TableB
myTable.update(tableRef);
}});}});}
Please, how can I fix it?

Update, the following code works:
function read(query, user, request) {
request.execute( { success: function(results) {
request.respond();
var countTable = tables.getTable('TableB');
countTable.where({date: results[0].Date}).read({
success: updateCount
});
function updateCount(results) {
if (results.length > 0) {
// tracking record was found. update and continue normal execution.
var trackingRecord = results[0];
trackingRecord.views = trackingRecord.views + 1;
countTable.update(trackingRecord);
} else {
console.log('error updating count');
}
}
}
});};

Related

Prisma: Finding items where two fields have the same value

I would like to find items in a Prisma db where the values for two columns are the same. The use case is to compare the 'created_at' and 'updated_at' fields to find items that have never been updated after their initial creation. In raw SQL I would do something like:
select updated_at,
cast(sign(sum(case when updated_at = created_at then
1
else
0
end)) as int) as never_modified
from tab
group by updated_at
Is it possible to achieve this in Prisma?
You would need to use Raw Queries to compare time values from the same table.
Here's an example of how you could achieve this, assuming a PostgreSQL database for the following query.
import { PrismaClient } from '#prisma/client'
const prisma = new PrismaClient()
async function initiateDatesComparisonRawQuery() {
const response =
await prisma.$queryRaw`SELECT * FROM "public"."Project" WHERE "created_at" = "updated_at";`;
console.log(response);
}
await initiateDatesComparisonRawQuery();
you can use the preview feature fieldReference of prisma.
schema.prisma
generator client {
provider = "prisma-client-js"
previewFeatures = ["fieldReference"]
}
your code
prisma.project.findMany({
where: { created_at: prisma.project.fields.updated_at }
})

Sequelize bulk update with inner join

I am currently working with Sequelize and can not figure out how to update bulk when im associating two tables together. I have the follow:
Tables:
members
user_id
channel_id
all
activities
user_id
channel_id
I am trying to update members.all when the user_ids match, members.channel_id is 2 and activities.channel_id is not 2.
Here is working Postgresql:
UPDATE members AS m
SET "all" = true
FROM activities AS a
WHERE m.user_id = a.user_id
AND m.channel_id = 2
AND a.current_channel != 2;
Is this possible to do is sequelize? How do include a.current_channel != 2 into my current update?
Member.update(
{ all: true },
{ where: { channel_id: channelId } },
)
When I try to add an include it does not work.
I think you can't do something like that using Sequelize update method. I would use the include option in a findAll method, but as far as I can see on the documentation, there is no include option for the update method.
You could use a raw query to use directly the query.
sequelize.query("UPDATE members AS m SET "all" = true FROM activities AS a WHERE m.user_id = a.user_id AND m.channel_id = 2 AND a.current_channel != 2").spread((results, metadata) => {
// Results will be an empty array and metadata will contain the number of affected rows.
});
Generally, i use this hack
models.findAll({
where: {
// which models to update
}
}).then(targets => {
models.target.update({
// your updates
},{
where : {
target_primary_key: targets.map(t => t.primary_key)
}
})
})

How to add item or value in assigned list to var?

I tried many ways but couldn't get the solution.
// linq query to getting 3 fields from table
var listData = (from row in db.table
orderby row.No ascending
select new {
row.Id,
row.No,
row.Type
}).ToList();
I want to add item or value to listData.
try Code:
var listData = (from row in db.table
select new
{
Id= row.Id,
No= row.No,
Type= row.Type
}
).OrderBy(c=>c.No).ToList();

Firebase: How to retrieve data from two tables using id

I come from an SQL background and recently started using Firebase for building an ionic shopping cart. This is the database schema:
To retrieve a user's cart, i used the following
var user_id="user1"; // Temporary initialised
var refCart = new Firebase("https://testing.firebaseio.com/cart");
var cart=$firebase(fireBaseData.refCart().child(user_id)).$asArray();
This gives the result:
item1 1
item2 2
item3 5
So tried using foreach()
var refMenu = new Firebase("https://testing.firebaseio.com/menu");
refCart.child(user_id).on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var item_id = childSnapshot.name();
var qty = childSnapshot.val();
//var data= refMenu.child(item_id).val();
// val is not a function
//var data= refMenu.child(item_id).exportval();
// exportval is not a function
//var data = $firebase (refMenu.child(item_id)). $asArray();
// Give me an array of objects , ie attributes - OK! But what to do next ?
//console.log("DATA",data );
console.log("Item",item_id+" "+qty);
});
});
How can i use item_id to retrieve item details.
Is it the correct way of doing data retrieval from multiple tables?
Update:
Using on() function , i managed to get the item attributes.
refMenu.child(item_id).on("value", function(snapshot) {
console.log("Price",snapshot.val().price);
});
But is there any better implementation for the same.
Is there any better ways to retrieve (from the server side) specific attributes for the item.
Like in SQL
SELECT name,price, ... from menu;
NOTE: .on('event', callback) method will call your callback every time the event is fired.
If you need to retrieve data from a reference once, you should use: .once('event', callback)
NOTE2: snapshot.val() will give you a JSON object that you can assign to a variable
I would do it this way:
refCart.child(user_id).on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var item_id = childSnapshot.name();
var qty = childSnapshot.val();
refMenu.child(item_id).once("value", function(snapshot) {
var item = snapshot.val()
console.log(item.name +' '+ item.price)
});
});
});
Hope it helps ;)

How to delete records that have same value in a column in Entity Framework?

I have a table in database that has some columns.I get a list of some records from this table in my repository class.So I will have something like this:
Now I want to delete records that have the same value in a special column(here in Code column),like this:
I mean I want to have just one of the records that have the same Code column value.
How can I do that in Entity Framework?
Let you are having two table Table1 and table2 and you want to delete all the records
from table1 which are having same code number in table2.
This is your requirement
1.first you have to get all the values of code column of table2
var x = db.table2.Select(p => p.code); Then you have to comapre it with table1
after that you have delete the records for those codes are same.
For that you have to write below piece of code.
foreach (var item in x)
{
var y = db.table1.Where(p => p.code== item).FirstOrDefault();
if (y != null)
{
db.table1.DeleteObject(y);
db.SaveChanges();
}
else
{
}
}
Group by the Code column, skip the first record of each group and delete the rest:
var query = db.Records.GroupBy(r => r.Code)
.Select(grouping => grouping.OrderBy(ent => ent.EntityId).Skip(1));
foreach (var element in query.SelectMany (q => q))
{
db.Records.Remove(element);
}
db.SaveChanges();