Laravel whereRaw - how to escape a '?' - laravel

Is there a way to escape a "?" in a eloquent whereRaw Statement? (Using laravel 6.x)
example:
ExampleModel::whereRaw(' "table"."json_field"::jsonb ?| array[\'test\', \'test2\'] ')->get();
This gets sent to the db as
where "table"."json_field"::jsonb $1| array['test', 'test2']
And well, thats not what i wanted to query...
Tried with '\?', put it in a binding (Laravel doc) - still no success.
Also i didn't find a reference in the docs ...
In my Usecase i want it to compare a json object with the psql comparing "?|" (Postgres Doc)
Thanks in advance!

the question is pretty old but my answer might help anyway.
The solution is very simple: just escape the questionmark with another questionmark.
The code of your example would look like this:
ExampleModel::whereRaw(' "table"."json_field"::jsonb ??| array[\'test\', \'test2\'] ')->get();
This solution has been tested with Laravel 7.28.3.

Didn't test but try using PDO:
$whereRaw = DB::connection()->getPdo()->quote(' "table"."json_field"::jsonb ?| array["test", "test2"] ');
ExampleModel::whereRaw($whereRaw)->get();

Well, didn't find an answer, but a workaround:
Don't use the question mark operators!
Instead i went for the named function. I found the named function via
SELECT
oprname,
oprcode || '(' || format_type(oprleft, NULL::integer) || ', '
|| format_type(oprright, NULL::integer) || ')' AS function
FROM pg_operator
WHERE oprname = '?|';
( Found there: big thanks to this guys post!)
So my Eloquent query now looks like:
ExampleModel::whereRaw('jsonb_exists_any("table"."json_field"::jsonb, array[\'test\', \'test2\'])')->get();
At least its working ¯\_(ツ)_/¯

Related

Get first letter of word in statement

I have a statement like "Animal Association" from the database. I want to get its short form. It means, only the first letter of each word like this "AA". In the blade file, I got the whole statement as follows,
<p>{{ $animal->user->club->name}}</p>
So, how can I get a short form of this name?
Thank You!
If you are using MySQL 8+, then a raw select with REGEXP_REPLACE should work here:
$users = DB::table('animals')
->select(DB::raw("SELECT REGEXP_REPLACE(name, '(\\w)\\w+\\s*', '$1')"))
->get();
This very common problem where we ran into, I can provide you a function that will solve your problem. I am sharing two solutions and you can use any of these solutions.
using function
You can use this function in your model and solve your problem.
public function getNameAbbreviate($string){
$abbreviation = "";
$string = ucwords($string);
$words = explode(" ", "$string");
foreach($words as $word){
$abbreviation .= $word[0];
}
return $abbreviation;
}
There is probably no one-line solution, the solution which I provided is readable and understandable.
using regex
This solution is easy to apply and in case you can't make the first method work then go with this.
<p>{{ preg_split("/\s+/", $animal->user->club->name) }}</p>
using regex we can get a direct solution but I personally don't like it or recommend it.

Trying to sum a groupBy value in Laravel 5.5

I have this code suggested to me. I am trying to sum the stock_in_qty and stock_out_qty.
$warehouse1stocks = Warehouse1stocks::select(
"order_item_id",
Warehouse1stocks::raw('SUM(stock_in_qty) as stock_in_qty'),
Warehouse1stocks::raw('SUM(stock_out_qty) as stock_out_qty'))->groupBy('order_item_id')->get();
// dd($warehouse1stocks);
return view("warehouse1.index", compact("warehouse1stocks", $warehouse1stocks));
My problem is this error
I tried to look for an answer from other questions here and I think my code seems ok but why am i still having that error?
what do you think is the problem with my code? thanks in advance!
Instead of writing:
Warehouse1stocks::raw('SUM(stock_in_qty) as stock_in_qty')
write:
DB::raw('SUM(stock_in_qty) as stock_in_qty')
when defining the write expressions
use this one
$warehouse1stocks = Warehouse1stocks::select(
"order_item_id",
\DB::raw('SUM(stock_in_qty) as stock_in_qty'),
\DB::raw('SUM(stock_out_qty) as stock_out_qty'))->groupBy('order_item_id')->get();
// dd($warehouse1stocks);
return view("warehouse1.index", compact("warehouse1stocks", $warehouse1stocks));

Laravel console: How to output variables using

I've seen this question but the solution therein doesn't use the Laravel method.
I wanna do something like this:
$this->info('This is the result: ', $result);
I believe you are looking for:
$output = new \Symfony\Component\Console\Output\ConsoleOutput(2);
$output->writeln('This is the result: ', $result);
Try this
$this->info('This is the result: ');
dump($result);
You can use dump() for print print objects
Btw, Do you know you can include variable inside double quote to output, the first basic thing of php.
$this->info("This is the result: {$result}")

Understanding evaluate function in OBIEE

I read some stuff on OBIEE Evaluate function and could not really understand as I am new to this.
EVALUATE('GetValue(%1,''SELECT MAX(P3_LST37) INTO :strValue FROM MV_ITEMSX WHERE ITEM_NUMBER = XXXX '' )' AS VARCHAR(2000), "Product")
Can you please help me to understand the function describe above?
Thanks
The Evaluate function enables you to send a function to the database to evaluate and return data to OBIEE. For security purposes you must use references in the function rather than the values themselves.
For example, if I have a column "Core"."Date" which returns the date as a string and want to use the TO_DATE function of evaluate, I would issue the following evaluate expression:
EVALUATE('TO_DATE(%1,'DD-MON-YYYY') AS DATE',"Core"."Date")
Hope that helps.

ruby one-liner for this possible?

Any chance the 2nd and 3rd lines can be combined in an one-liner and hopefully save one valuable?
def self.date_format
record = find_by_key('strftime')
record ? record.value : "%Y-%b-%d'
end
the above function in a Config model try to fetch a database record by a key, return a default if not found in database.
Even better if can be written in named scope. Thanks
As requested.
Nobody yet has mentioned try, which is perfect for this situation:
value = find_by_key('strftime').try(:value) || "%Y-%b-%d"
You could use:
(find_by_key('strftime').value rescue nil) || "%Y-%b-%d"
though using exceptions is not very efficient.
Does
value = find_by_key('strftime') || "%Y-%b-%d"
work for you?
Do you need to assign a "value" variable at all? If not...
def self.date_format
find_by_key('strftime') || "%Y-%b-%d"
end

Resources