knex json object WHERE condition - sql

I have sql jsonb column in db named 'car' with structure
[{'brand':'audi', 'year':'2001'}] --> how to filter WHERE brand=audi?
this doesn't seem to be right:
return await db(db_table)
.select('*')
.whereRaw('car->>$.?? = ?', ['brand', 'audi']);
#felixmosh

Since your object is an array of objects, your suggested code won't work.
Try something like this:
return await db(db_table)
.select('*')
.whereRaw('car->>$[0].?? = ?', ['brand', 'audi']);
// ----------------^ this selects the first element of the array

Related

How to delete items from an array in Vue

I have a function called updateAnswer with multiple dynamic parameters.
updateAnswer(key, answer, array = false) {
if (array) {
if(this.answers.contains.find(element => element === answer)) {
//Delete item from array if already element already exists in this.answers.contains array.
} else {
Vue.set(this.answers, key, [...this.answers.contains, answer]);
}
} else {
Vue.set(this.answers, key, answer);
}
},
I'd like to know how delete an item in the array if the value already exists in the array.
You can use method called splice:
Just reference on your array and set values in the brackets the first is referenced on the position, the second is how many datas you want to splice/delete.
The function looks like this:
this.array.splice(value, value)
Lets see on an example - you have array food= [apple, banana, strawberry] than I'm using this.food.splice(1,1)..
my array looks now like this food = [apple, strawberry] - first value in my brackets are the position, the second one is the amount of "numbers" you want to delete.
Hopefully this helps you out!
I suppose each value in this.answers.contains is unique?
Anyways, if you just want to delete the item if already exists, I suggest filter(). It should look like below:
if(this.answers.contains.find(element => element === answer)) {
this.answers.contains = this.answers.contains.filter(c => c !== answer)
}
Also, the if condition if(this.answers.contains.find(element => element === answer)) could also be replaced by if(this.answers.contains.includes(answer))
Hope that could help you.

Remove bracket and quotations in JSON_AGG (Aggregate Functions)

public function fetchdrug(Request $search_drug){
$filter_drug = $search_drug->input('search_drug');
$all_drugs = HmsBbrKnowledgebaseDrug::selectRaw('DISTINCT ON (drug_code)
drug_code,
drug_name,
JSON_AGG(drug_dosage) AS dosage_list')
->GroupBy('drug_code', 'drug_name')
->orderBy('drug_code', 'ASC')
->get();
return response()->json([
'all_drugs'=>$all_drugs,
]);
}
I am using JSON_AGG to retrieve multiple lines of drug_dosage and combine them into one, but I am getting a bracket and quotation in my output, how do I take it out?
UPDATE:
I am getting errors in the examples because I am trying solutions using str_replace and preg_replace. my problem is that the target is in an SQL statement so I am suspecting that has something to do with the error since there is other data in the result
Error:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
{"drug_code":"CFZU",
"drug_name":"Cefazolin",
"dosage_list":"[\"<=4 mg\/L\", \"<=3 mg\/L\"]"},
{"drug_code":"TZPD","drug_name":"Pip\/Tazobactam",
"dosage_list":"[\"Pip\/Tazobactam\"]"}
You can try string_agg instead JSON_AGG
public function fetchdrug(Request $search_drug){
$filter_drug = $search_drug->input('search_drug');
$all_drugs = HmsBbrKnowledgebaseDrug::selectRaw('DISTINCT ON (drug_code)
drug_code,
drug_name,
string_agg(drug_dosage, ', ') AS dosage_list')
->GroupBy('drug_code', 'drug_name')
->orderBy('drug_code', 'ASC')
->get();
return response()->json([
'all_drugs'=>$all_drugs,
]);
}
Because: JSON_AGG returns JSON ARRAY as STRING. After that you returned json encoded result from controller. This adds unwanted characters for make valid json encoding. (nested quotes must be escaped).
So;
Before sending result, you must json_decode for each record's drug_dosage field.
Example code:
public function fetchdrug(Request $search_drug){
$filter_drug = $search_drug->input('search_drug');
$all_drugs = HmsBbrKnowledgebaseDrug::selectRaw('DISTINCT ON (drug_code)
drug_code,
drug_name,
string_agg(drug_dosage, ', ') AS dosage_list')
->GroupBy('drug_code', 'drug_name')
->orderBy('drug_code', 'ASC')
->get();
foreach($all_drugs as $drug){
//decode postgresql 'json array like string presentation' to array.
$decoded = json_decode($drug->drug_dosage);
// if you want to remove null/empty values use array_filter
$filtered = array_filter($decoded); // default behavior removes falsy values.
// use same field to hold wanted, structured values
$drug->drug_dosage = $filtered;
}
// And return as json response like before.
return response()->json([
'all_drugs'=>$all_drugs,
]);
}

Linq2DB can't translate a mapped column in Where clause

I'm working with a legacy Oracle database that has a column on a table which stores boolean values as 'Y' or 'N' characters.
I have mapped/converted this column out like so:
MappingSchema.Default.SetConverter<char, bool>(ConvertToBoolean);
MappingSchema.Default.SetConverter<bool, char>(ConvertToChar);
ConvertToBoolean & ConvertToChar are simply functions that map between the types.
Here's the field:
private char hasDog;
[Column("HAS_DOG")]
public bool HasDog
{
get => ConvertToBoolean(hasDog);
set => hasDog = ConvertToChar(value);
}
This has worked well for simply retrieving data, however, it seems the translation of the following:
var humanQuery = (from human in database.Humans
join vetVisit in database.VetVisits on human.Identifier equals vetVisit.Identifier
select new HumanModel(
human.Identifier
human.Name,
human.HasDog,
vetVisit.Date,
vetVisit.Year,
vetVisit.PaymentDue
));
// humanQuery is filtered by year here
var query = from vetVisits in database.VetVisits
select new VetPaymentModel(
(humanQuery).First().Year,
(humanQuery).Where(q => q.HasDog).Sum(q => q.PaymentDue), -- These 2 lines aren't correctly translated to Y/N
(humanQuery).Where(q => !q.HasDog).Sum(q => q.PaymentDue)
);
As pointed out above, the .Where clause here doesn't translate the boolean comparison of HasDog being true/false to the relevant Y/N values, but instead a 0/1 and results in the error
ORA-01722: invalid number
Is there any way to handle this case? I'd like the generated SQL to check that HAS_DOG = 'Y' for instance with the specified Where clause :)
Notes
I'm not using EntityFramework here, the application module that this query exists in doesn't use EF/EFCore
You can define new mapping schema for your particular DataConnection:
var ms = new MappingSchema();
builder = ms.GetFluentMappingBuilder();
builder.Entity<Human>()
.Property(e => e.HasDog)
.HasConversion(v => v ? 'Y' : 'N', p => p == 'Y');
Create this schema ONCE and use when creating DataConnection

Silverstripe 3 filter ArrayList

How can we filter an ArrayList in Silverstripe 3?
where getVideosfromCategories() returns a merged ArrayList
I need something Like:
$this->getVideosfromCategories()->filter('ID:LessThan', $id)->sort(array('ID' => 'DESC'))->first()
these Filters (filter('ID:LessThan', $id)) only work with DataList ?
How can i filter my ArrayList?
these Filters (filter('ID:LessThan', $id)) only work with DataList ?
Yep, that's correct, search filter modifiers only work on DataList instances.
(https://docs.silverstripe.org/en/3/developer_guides/model/searchfilters/) It's interesting that the documentation does not mention that, I think it should be updated.
(I opened a PR for it https://github.com/silverstripe/silverstripe-framework/pull/9363)
But you can modify your current code to filter by an array of IDs instead, something like this:
$idsWeWant = [];
if ($id > 0) {
$idsWeWant = range(0, $id - 1); // "$id - 1" because you had "LessThan" modifier.
}
$this->getVideosfromCategories()
->filter('ID', $idsWeWant)
->sort(array('ID' => 'DESC'))
->first();

how to get last inserted id - zend

I'm trying to get latest inserted id from a table using this code:
$id = $tbl->fetchAll (array('public=1'), 'id desc');
but it's always returning "1"
any ideas?
update: I've just discovered toArray();, which retrieves all the data from fetchAll. The problem is, I only need the ID. My current code looks like this:
$rowsetArray = $id->toArray();
$rowCount = 1;
foreach ($rowsetArray as $rowArray) {
foreach ($rowArray as $column => $value) {
if ($column="id") {$myid[$brr] = $value;}
//echo"\n$myid[$brr]";
}
++$rowCount;
++$brr;
}
Obviously, I've got the if ($column="id") {$myid[$brr] = $value;} thing wrong.
Can anyone point me in the right direction?
An aternative would be to filter ID's from fetchAll. Is that possible?
Think you can use:
$id = $tbl->lastInsertId();
Aren't you trying to get last INSERT id from SELECT query?
Use lastInsertId() or the value returned by insert: $id = $db->insert();
Why are you using fetchAll() to retrieve the last inserted ID? fetchAll() will return a rowset of results (multiple records) as an object (not an array, but can be converted into an array using the toArray() method). However, if you are trying to reuse a rowset you already have, and you know the last record is the first record in the rowset, you can do this:
$select = $table->select()
->where('public = 1')
->order('id DESC');
$rows = $table->fetchAll($select);
$firstRow = $rows->current();
$lastId = $firstRow->id;
If you were to use fetchRow(), it would return a single row, so you wouldn't have to call current() on the result:
$select = $table->select()
->where('public = 1')
->order('id DESC');
$row = $table->fetchRow($select);
$lastId = $row->id;
It sounds like it's returning true rather than the actual value. Check the return value for the function fetchAll