I don't know what I am doing wrong but I assume it's something right under my nose.
I am trying to retrieve multiple rows from a database by their ID, by subtracting a number from the original query like so:
$week4 = DB::table('weekly_territory_data')->where([['area_id', '=', $area_id], ['start_date', '=', $startDate]])->first();
Log::info(print_r($week4, true));
$selectedWeekId = $week4->id;
$selectedWeekIdSub2 = $selectedWeekId - 236;
$selectedWeekIdSub3 = $selectedWeekId - 472;
$selectedWeekIdSub4 = $selectedWeekId - 708;
Log::info($selectedWeekIdSub4);
$week1 = DB::table('weekly_territory_data')->where('id', '=', $selectedWeekIdSub4)->first();
Log::info(print_r($week1,true));
I know I am getting the right ID numbers, but I can't retrieve the rows using the code I have. What is going on here? Is there some sort of exact case issue?
I strongly recommend using Eloquent,
Assuming you created a model WeeklyTerritoryData
your query should look like this :
$week1 = WeeklyTerritoryData::find($selectedWeekIdSub4)->first();
or
$week1 = WeeklyTerritoryData::where('id',$selectedWeekIdSub4)->first();
this will return a Collection, then you can access id or any other field like this :
$week1->id
The issue was typecasting.
I was trying to get the data set with an ID, treating it as an integer... but my ID column is a string for some stupid reason.
$selectedWeekId = $week4->id;
$week3id = $selectedWeekId - 236;
$week3string = (string) $week3id;
$week3 = WeeklyTerritoryData::where('id', '=', $week3string)->get();
Log::info('week3 to follow');
Log::info($week3);
$week2id = $selectedWeekId - 472;
$week2string = (string) $week2id;
$week2 = WeeklyTerritoryData::where('id', '=', $week2string)->get();
Log::info('week2 to follow');
Log::info($week2);
$week1id = $selectedWeekId - 708;
$week1string = (string) $week1id;
$week1 = WeeklyTerritoryData::where('id', '=', $week1string)->get();
Related
Am using a dynamic query to get data. Below is my code
if(objVal != null){
sObject obj = Schema.getGlobalDescribe().get(objVal).newSObject();
if(ConditionVal== null || ConditionVal=='')
query = 'Select Id From '+objVal+ ' Limit 10000';
else{
ConditionVal= String.escapeSingleQuotes(ConditionVal);
query = 'Select Id From '+selectedObj+' WHERE '+ConditionVal+' LIMIT 10000';
}
List<SObject> objlst = Database.query(query);
Am getting "objVal" , "ConditionVal" value form VF page
Example objVal = 'Account' ConditionVal = 'industry = 'Apparel'
after executing the code am getting the query like this
Select Id From Account WHERE industry = \'Apparel\' LIMIT 10000
update the value of ConditionVal variable as below,
ConditionVal = 'Industry = \'Apparel\'';
the query will work as expected.
Using Nodejs and mssql package for SQL Server, I understand normal SELECT query with parameters:
aVar = "somestring"; // used as example, the real input is from a web form
request = new sql.Request(conn)
.input('aParam', sql.NVarChar(200), aVar);
q = "SELECT * FROM myTable WHERE theColumn = #aParam";
request.query(q, function(err, record) { ...
Those work just fine. Changing this to use LIKE, and I cannot get it to work. I've tried single quote before the % character, after, around it, just around the string, the whole thing, etc. Doing this:
q = "SELECT * FROM myTable WHERE theColumn LIKE " + "'%#aParam%'";
does not result in any errors, but returns no results. All other attempts with those single quotes results in query syntax errors. I cant seem to locate any documentation for parameterizing queries with wildcards. Where am I going wrong with this?
The syntax to do this is mentioned here - https://github.com/tediousjs/node-mssql/issues/332.
But in short:
q = `SELECT * FROM myTable WHERE theColumn LIKE '%' + #aParam + '%';`;
Unless you writing low level driver/worker, I would recommend to use any ORM:
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password');
const MyTable = sequelize.define('myTable', {
theColumn: Sequelize.STRING
});
const aVar = 'somestring';
const results = await MyTable.findAll({
where: {
theColumn: { $like: `%${aVar}%` }
}
});
})
console.dir(results);
await can be used only inside async functions. For Framework supporting this out of the box take a look at Koa.js https://github.com/koajs/koa
I´m trying to optimize some process in my application but I´m stuck with this problem. My application is working so the entity mapping is correct. Simplifying what I´m trying to do is this:
using (var offCtx = new CheckinOfflineEntities())
{
using (var trans = offCtx.Database.BeginTransaction(IsolationLevel.Snapshot))
{
DateTime purgePivot = DateTime.Now.AddDays(-2);
count = offCtx.Database.ExecuteSqlCommand(#"select L.* into #NewLegs from InventoryLeg L where L.STDUTC >= {0}", purgePivot);
long d = offCtx.Database.SqlQuery<long>("select count(*) from #NewLegs").FirstOrDefault();
}
}
I´m selecting some data I want to delete from one table, storing it in a temporary table so that I can use this temporary table in other queries to exclude related data.
The problem is, when I try to use the temporary table I´m receiving the exception SqlException: "Invalid object name '#NewLegs'."
Thank you for your time.
You can merge the query like this.
And count returns int, not long.
COUNT always returns an int data type value. - MSDN
var query = string.Format("{0} {1}",
#"select L.* into #NewLegs from InventoryLeg L where L.STDUTC >= #STDUTC",
#"select count(*) from #NewLegs")
var d = offCtx.Database.SqlQuery<int>(query, new SqlParameter("STDUTC", purgePivot))
.FirstOrDefault();
I realy don´t know why but removing the parameter and adding it in the query solved the problem.
The code below works fine:
using (var offCtx = new CheckinOfflineEntities())
{
using (var trans = offCtx.Database.BeginTransaction(IsolationLevel.Snapshot))
{
DateTime purgePivot = DateTime.Now.AddDays(-2);
count = offCtx.Database.ExecuteSqlCommand(#"select L.* into #NewLegs from InventoryLeg L where L.STDUTC >= " + purgePivot.toString("yyyy-mm-dd HH:mm:ss");
long d = offCtx.Database.SqlQuery<long>("select count(*) from #NewLegs").FirstOrDefault();
}
}
I am trying to update data using below code but it is generating wrong SQL query. don't understand why it is generating wrong one. Please help me out.
$data = array();
$data['Pers']['etat'] = 1;
$data['Pers']['Activation'] = '';
$this->Pers->id = $results['Pers']['persID'];
$this->Pers->save($data);
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'bdr+.pers.persID' in
'where clause'
SQL Query: UPDATE `bdr+`.`pers` SET `etat` = 1, `Activation` = '',
`date_time` = '2014-03-19 11:33:21' WHERE `bdr+.pers.persID` = 37
It means bdr+.pers.persID is generating wrong. Don't understand why it is generating like this.
check if this $results['Pers']['persID'] variable if it is returning a proper format
then try this
$data = array();
$data['Pers']['persID'] = $results['Pers']['persID'];
$data['Pers']['etat'] = 1;
$data['Pers']['Activation'] = '';
//Just to make sure your model is loaded
$this->loadModel('Pers');
if ($this->Pers->save($data, false)) {
echo 'Pres has been saved :) ';
}
Your code containing bdr+.pers.persID` = '37' because $results['Pers']['persID'] supplying 37
I have a Code column of type varchar in database, which includes numbers only. I use the method below to get the next code, and it works fine. But I prefer all the calculations and type conversions to be done on SQL side, to have less overhead. Using the code below, I retrieve all data, which is not needed. Any ideas is really appreciated.
public string GetNextCode(int type)
{
var codeList = (from o in ObjectQuery
where o.Type == Type
select o.Code).ToList<string>();
List<int> list = codeList.Select(int.Parse).ToList();
int nextDL = list.Max() + 1;
return nextDL.ToString();
}
You could try something like the below, it orders the result set descending by the Code and then grabs the first result. Please note I haven't tested this but I think it should work.
var codeList = (from o in ObjectQuery
where o.Type == Type
select o.Code).OrderByDescending(
x => x.Code).First()
Instead of OrderByDescending().First() you could also use OrderBy().Last()
This is a solution I came up with:
var max = (from o in ObjectQuery
let num = ObjectQuery.Where(i => i.Type == Type).Select(i => i.Code).Cast<int>().Max()
select num).FirstOrDefault() + 1;
return max.ToString();