Remove bracket and quotations in JSON_AGG (Aggregate Functions) - sql

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,
]);
}

Related

knex json object WHERE condition

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

Rewriting SQL query in Laravel but getting error BadMethodCallException: Call to undefined method

I'm trying to do this query in Laravel.
SELECT DISTINCT curriculum.Course_Code, transcript.Course_Grade, transcript.Course_Comp, transcript.CWID
FROM curriculum
LEFT JOIN transcript
ON curriculum.Course_Code = transcript.Course_Code AND transcript.CWID = "C38475920";
Except I'm no longer using the static CWID ->"C38475920". This is what I have:
public function getProgress($id){
return DB::table('curriculum')
->select('curriculum.Course_Code','transcript.Course_Comp', 'transcript.Term_Completed', 'transcript.Course_Grade')
->distinct('curriculum.Course_Code')
->leftJoin('transcript', 'curriculum.Course_Code','=','transcript.Course_Code')
->on('CWID', '=', $id)
->get();
}
The function gives this error BadMethodCallException: Call to undefined method Illuminate\Database\Query\Builder::on() in file
Do I have to add something to my model to use ON?
If you would like to use a "where" style clause on your joins, you may use the where methods on a join. Instead of comparing two columns, these methods will compare the column against a value.
The selectRaw method can be used in place of select(DB::raw(...)). This method accepts an optional array of bindings as its second argument.
DB::table('curriculum')
->selectRaw('DISTINCT curriculum.Course_Code, transcript.Course_Grade, transcript.Course_Comp, transcript.CWID')
->leftJoin('transcript', function ($leftJoin) use ($id) {
$leftJoin->on('curriculum.Course_Code', '=', 'transcript.Course_Code')
->where('transcript.CWID', '=', $id);
})
->get();

How to return a JSON array from sql table with PhalconPHP

I have several tables that have JSON arrays stored within fields.
Using PHP PDO I am able to retrieve this data without issue using:
$query1 = $database->prepare("SELECT * FROM module_settings
WHERE project_token = ? AND module_id = ? ORDER BY id DESC LIMIT 1");
$query1->execute(array($page["project_token"], 2));
$idx = $query1->fetch(PDO::FETCH_ASSOC);
$idx["settings"] = json_decode($idx["settings"]);
This returns a string like:
{"mid":"","module_id":"1","force_reg_enable":"1","force_reg_page_delay":"2"}
Attempting to gather the same data via PhalconPHP
$result = Modulesettings::findFirst( array(
'conditions' => 'project_token = "' . $token . '"' ,
'columns' => 'settings'
) );
var_dump($result);
Provides a result of
object(Phalcon\Mvc\Model\Row)#61 (1) { ["settings"]=> string(167) "{"text":"<\/a>
<\/a>
","class":""}" }
What do I need to do different in Phalcon to return the string as it is stored in the table?
Thank you.
You have 2 approach
First :
Get the settings with this structure :
$settings = $result->settings;
var_dump($settings);
Second :
First get array from resultset, then using the array element :
$res = $result->toArray();
var_dump($res['settings']);
Try it.
You can decode json right in your Modulesettings model declaration:
// handling result
function afterFetch() {
$this->settings = json_decode($this->settings);
}
// saving. Can use beforeCreate+beforeSave+beforeUpdate
// or write a Json filter.
function beforeValidation() {
$this->settings = json_encode($this->settings);
}

pdo is not returning an output. Fatal error: Call to a member function fetch() on a non-object in C:\webroot\wamp\www\index.php on line 12

<?php
$config['db'] = array (
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'pdologin'
);
$db = new PDO("mysql:host={$config['db']['host']};dbname={$config['db']['dbname']}",
$config['db']['username'], $config['db']['password']);
$query = $db->query("SELECT * 'firstname' FROM 'login'");
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
echo $row['firstname'], '<br>';
}
?>
When I run the code I get error "Fatal error: Call to a member function fetch() on a non-object in C:\webroot\wamp\www\index.php on line 12".
Whats making it error? The only thing I can think of is the SQL query.
This SQL query has two syntax errors in it:
$query = $db->query("SELECT * 'firstname' FROM 'login'");
You can't use a string literal as a table in the FROM clause.
Explanation: different types of quotes do different things in SQL.
Single-quotes are always delimiters for string literals or date literals.
In MySQL, back-ticks are delimiters for table identifiers (as well as columns and other metadata objects).
Double-quotes are delimiters for table identifiers in standard SQL, and in MySQL if you set SQL_MODE=ANSI_QUOTES. But by default in MySQL, double-quotes are the same as single-quotes, delimiting strings and dates.
You also had 'firstname' in your query in an invalid place. I can't tell if you meant that to name a column (if so, you were getting the quote type wrong again), or if you meant it to be a column alias (if so, you can't alias *, you can only alias a single specific column).
So your query should look like this:
$query = $db->query("SELECT * FROM `login`");
Another mistake in your script is that you don't verify that $query is an object of type PDOStatement before calling PDOStatement methods on it. PDO::query() will return false if there was an error in the SQL. false is a primitive value, not an object, so it will naturally not have any methods you can call. So you always have to check the return value before doing anything else with it.
For example:
$query = $db->query("SELECT * FROM `login`");
if ($query === false) {
die(print_r($db->errorInfo(), true));
}

Trying to get property of non-object Yii

I dont get this error, there is a row in database.
$tip = StringHelper::trimmer($_GET['tip']);
$sql = 'SELECT id FROM contact_reasons WHERE alias = "' . $tip . '"';
$model = ContactReasons::model()->findAllBySql( $sql );
die($model->id);
if(!is_null($model)) {
$this->render('kontakt', array(
'model' => $model,
));
} else {
$this->renderText('Tražena stranica ne postoji.');
}
I used debug to see if there is a response, and even used query on database, and it returns a row with ID. I get this error on line with die();
Please note that, findAllBySql returns an array of CActiveRecords, while findBySql returns a single CActiveRecord. You may also use parameter binding for your SQL statements to prevent SQL injection.
see also http://www.yiiframework.com/doc/api/1.1/CActiveRecord