I need create multiply search by years. From request I get string like 2017,2018 and then I want get Questions which createdAt, between from start year and end year. I have query builder with part, and I'am not understand why I have this error
if ($paramFetcher->get('years')) {
$orXSearch = $qb->expr()->orX();
$yearData = trim($paramFetcher->get('years'));
foreach (explode(',', $yearData) as $key => $id) {
if (!$id) {
continue;
}
$orXSearch
->add($qb->expr()->between('q.createdAt', ':'.$key.'dateFrom', ':'.$key.'dateTo'));
$date = $this->additionalFunction->validateDateTime($id, 'Y');
$first = clone $date;
$first->setDate($date->format('Y'), 1, 1);
$first->setTime(0, 0, 0);
$last = clone $date;
$last->setDate($date->format('Y'), 12, 31);
$last->setTime(23, 59 , 59);
$qb
->setParameter($key.'dateFrom', $first->format('Y-m-d H:i:s'))
->setParameter($key.'dateTo', $last->format('Y-m-d H:i:s'));
}
$qb->andWhere($orXSearch);
}
error:
symfony Invalid parameter format, : given, but :<name> or ?<num> expected.
In your foreach loop, you’re looping over the result of an explode operation which yields a numeric array, i.e. $key will always have a numeric value.
Hence, your parameter placeholder is colon + number + string, i.e. :1dateFrom. This is not allowed. Either you reference a string value with a colon + string placeholder (:foo), or you reference a numeric value with a question mark + number value (?1).
Your problem is easy to solve: Simply add any letter between the colon and the number, and you’re good:
->add($qb->expr()->between(
'q.createdAt',
':x'.$key.'dateFrom',
':x'.$key.'dateTo'
));
Related
I want to insert data into a middle table Builds_Perks with columns idBuild and idPerks. The problem is with idPerks, I take the id from some checkbox and when I want to isnert those id the following error appears:
Argument 2 passed to App\Entity\BuildsPerks::__construct() must be an instance of App\Entity\Perks, int given...
This is part of the code where I take the checkbox id to INSERT them:
$idAllPerks = $request->get('chk');
foreach($idAllPerks as $idPerk) {
$idPerkInt = (int) $idPerk; // string into int
$newBuildPerk = new BuildsPerks(
$usuBuild,
$idPerkInt
);
$this->getDoctrine()->getManager()->persist($newBuildPerk );
}
Thanks.
The error message is very clear. It expects to receive an object of type Perks but you are giving the ID of that object instead of the object itself. This might work.
$idAllPerks = $request->get('chk');
foreach($idAllPerks as $idPerk) {
$em = $this->getDoctrine()->getManager();
$perk = $em->getRepository(Perks::class)->find((int) $idPerk);
$newBuildPerk = new BuildsPerks(
$usuBuild,
$perk
);
$em->persist($newBuildPerk );
}
I have a strange problem, I am making a conditional query with values stored in different variables and passing them to where clause. That where clause simply not accepting values and keep on saying undefined variable in very first condition. To understand it I just cut it to one condition and make it simple to get easy answers.
Error: ErrorException: Undefined variable: col_name in file E:\xampp\htdocs\coder\app\Http\Controllers\a26_gets\a26_gets_ctrl.php on line 97
Code:
$this->tableName = 'mytable';
$col_name = 'first_name';
$value = 'danny';
$tableData = DB::table($this->tableName)
->when($value, function ($query, $value) {
return $query->where($col_name, $value);
})->paginate(1);
print_r($tableData);
Try adding the $col_name to the scope of the conditional query...
$this->tableName = 'mytable';
$col_name = 'first_name';
$value = 'danny';
$tableData = DB::table($this->tableName)
->when($value, function ($query, $value) use ($col_name) {
return $query->where($col_name, $value);
})->paginate(1);
print_r($tableData);
I completely understand that this is because LINQ query requires the whole expression to be translated to a server , and therefore I cant call an outside method in it. but as I have looked at other answers there is not relative solution to this. the only approach that I thought about is to loop through all the items in the model and than passing them to the query one by one but even though this approach would not help so I am seeking help in here for anyone to help me to figure out how to call a method or a way of calling a method appendstr that initializes a.PostedDate before checking its actual equivalent value in the giving LINQ Query.
[HttpGet]
public ActionResult SearchResult(int? page, string searchTitle = null, string searchLocation = null, string last24 = "")
{
ViewBag.searchTitle = searchTitle;
ViewBag.searchLocation = searchLocation;
ViewBag.page = page;
ViewBag.last24 = last24;
setUpApi(searchTitle, searchLocation);
var result = new List<AllJobModel>().AsQueryable();
if (!string.IsNullOrEmpty(ViewBag.searchTitle) || !string.IsNullOrEmpty(ViewBag.searchTitle) || !string.IsNullOrEmpty(ViewBag.last24))
{
setUpApi(searchTitle, searchLocation);
DateTime now = DateTime.Now;
result = db.AllJobModel.Where(a => a.JobTitle.Contains(searchTitle) && a.locationName.Contains(searchLocation) &&
appendstr(a.PostedDate).Equals(now.AddHours(-24).ToString("MM-dd-yyyy")));
}
else
{
result = from app in db.AllJobModel select app;
}
return View(result.ToList().ToPagedList(page ?? 1, 5));
}
The second method that gets called in the LINQ Query
public string appendstr(string str)
{
var x = str.Split(' ');
return 01 + "-" + x[1] + "-" + x[2];
}
I think you already understand that the .NET code you write in the Where clause is actually an expression that is parsed and converted to SQL. So if you have a funky string manipulation method, you can't use it directly.
The brute force option, as you seem to already understand, it to materialize the query first and then run the C# code over the results. You can do this with ToList() or AsEnumerable().
result = db.AllJobModel
.Where
(
a => a.JobTitle.Contains(searchTitle)
&& a.LocationName.Contains(searchLocation)
)
.AsEnumerable()
.Where
(
a => appendstr(a.PostedDate).Equals(now.AddHours(-24).ToString("MM-dd-yyyy")))
);
However in your specific case you can try a trick. You are attempting a date comparison, which SQL is perfectly capable of doing... you just need to convert that funky PostedDate to a SQL DateTime so that you can compare it directly. The gimmick for that is to use SqlFunctions.DateAdd to add null interval (e.g. 0 days). This implicitly converts the string to DateTime, where you can now query on the SQL side:
var targetDate = DateTime.Now.AddHours(-24);
result = db.AllJobModel
.Where
(
a => a.JobTitle.Contains(searchTitle)
&& a.LocationName.Contains(searchLocation)
&& SqlFunctions.DateAdd("DAY", 0, a.PostedDate) == targetDate
);
Credit goes to this post for the workaround.
I've been using a bit of arithmetic in the Body Mapping Template in Integration Request:
#set($now = $context.requestTimeEpoch/1000)
#set($soon = $now + 600)
{
"TableName": "events",
.... [ here get events between $now and $soon]
}
Recently I came to need to pass an offset through a parameter:
#set($now = $context.requestTimeEpoch/1000)
#set($soon = $now + $input.params('offset'))
{
"TableName": "events",
.... [ here get events between $now and $soon] ....
}
It turns out that if $now is 1518939082, with query paramter ?offset=600 $soon will be 1518939082600 - a concatenation. I have tried various ways to force the parameter being recognised as an integer, including:
#set($offset = $Integer.parseInt($input.params('offset')))
#set($offset = 0 + $input.params('offset'))
#set($offset = 1 * $input.params('offset'))
None of them works. I inserted #set($offset = 0) before each test so I can tell "nothing happens" from "a nothingness is returned".
In the first case, $offset prints an empty string, not 0. (This happens to $Integer.parseInt("1") too.)
In the second case, $offset prints a concatenation of "0" and the string value of "offset".
In the third case, $offset prints a 0, as if the entire line doesn't exist.
None of them successfully transformed the parameter to an integer.
Is there a way to use that parameter as an integer?
I have been trying to set a value containing a percentage sign in PHPExcel.
I couldn't find how to escape it at all and all searches point me to how to format a percentage, but that's not what I need.
My current problem is:
$cell = 'Z12';
$value = '=Y12-(Y12*20%)';
$excel->setActiveSheetIndex(0)->setCellValue($cell, $value);
This problem is specific to the Excel5 Writer, the percentage operator works correctly in other writers.
I'm about to push a fix to github, but in the meanwhile you can edit the Classes/PHPExcel/Writer/Excel5/Parser.php file.
Lines 1431-1437 currently read:
if($this->_lookahead == '%'){
$result = $this->_createTree('ptgPercent', $this->_current_token, '');
} else {
$result = $this->_createTree($this->_current_token, '', '');
}
$this->_advance();
return $result;
Modify these with an extra call to $this->_advance(); for the % operator lookahead branch:
if($this->_lookahead == '%'){
$result = $this->_createTree('ptgPercent', $this->_current_token, '');
$this->_advance(); // Skip the percentage operator once we've pre-built that tree
} else {
$result = $this->_createTree($this->_current_token, '', '');
}
$this->_advance();
return $result;