Laravel Query Builder: whereExists translates condition clause to question mark - laravel

If I have the following query built using the Query Builder:
$q = DB::table('Products')->whereExist(function ($q)
{
$q->select(DB::raw(1))
->from('tags_products')
->where('products.PorductId', '=', 'tags_products.ProductID');
});
The translated SQL using $q->toSql(); that is:
select * from `Products` where `exist` = (select 1 from `tags_products` where `products`.`ProductID` = ?)
Apparently, the Query Builder translates tags_products.ProductID to ?.
Why does it become "?" ?

As #Jared Eitnier very well pointed out, Laravel uses PDO to bind the parameters you pass to the Query Builder methods. However, because when you use where the third parameter represents the value, Laravel will not treat it as a column unless you explicitly tell it to, otherwise it will treat 'tags_products.ProductID' as a regular string value. So you have two options here:
1. Use DB::raw() to let the Query Builder know that the value is not a string that requires escaping:
->where('products.PorductId', '=', DB::raw('tags_products.ProductID'));
2. Use whereRaw() which will allow you to write a raw SQL statement:
->whereRaw('products.PorductId = tags_products.ProductID');

These are mysql prepared statements.
See What is the question mark's significance in MySQL at "WHERE column = ?"?
Laravel uses mysql's PDO.

Related

Laravel - WhereExists returning "Invalid parameter number: parameter was not defined"

I'm trying to use whereExists() on an existing Eloquent query builder (called $trips):
$trips = $trips->whereExists(function ($query) use ($filterValue) {
$query->from(DB::raw("jsonb_array_elements(passengers->'adults'->'persons') as p(person)"))
->whereRaw("p.person->>'name' LIKE '?%'", $filterValue);
});
The query I'm trying to create in raw postgres format is the following (this query works fine using pgAdmin):
SELECT *
from trips
WHERE exists (select *
from jsonb_array_elements(passengers -> 'adults' -> 'persons') as p(person)
where p.person ->> 'name' LIKE 'Prof%');
And I'm receiving this error:
Invalid parameter number: parameter was not defined
I think the problem is small, but I can't see it myself.
The parameter definition in your whereRaw() statement is not quite correct. Parameterized queries are not just string replacements. Your query as written doesn't have a parameter in it, it has a string literal of '?%'. You need to change this to a query parameter, and append the % wildcard to the string you pass in.
Try this:
->whereRaw("p.person->>'name' LIKE ?", $filterValue.'%')

Eloquent ORM does not allow ? operator used in JSONB lookup

Is it possible to run this postgres query with Eloquent ORM?
select * from "table" where "column"->'key' ? '1'
It throws error for using ? in the query. Is there any alternative approach?
You can use jsonb_exists function. All question marks determines as placeholder for prepared statements.
Or in php 7.4 you can use ?? (answer here: How to use Postgres jsonb '?' operator in Laravel with index support?)
Use a raw query instead:
DB::raw(" select * from \"table\" where \"column\"->'key' ? '1' ");

How can I write this query using the laravel query builder?

I'm on laravel 5.1 using postgres as the DB. I have a fiddle here in case it helps understand my issue: https://www.db-fiddle.com/f/5ELU6xinJrXiQJ6u6VH5/4
with properties as (
select
properties.*,
json_agg(property_fields.*) as property_fields
from
properties
left join fields as property_fields
on property_fields.parent = 'property' and property_fields.parent_id = properties.id
group by properties.id, properties.deal_id, properties.address
)
select
deals.*,
json_agg(properties.*) as deal_properties,
json_agg(deal_fields.*) as deal_fields
from deals
left join properties on deals.id = properties.deal_id
left join fields deal_fields on deal_fields.parent = 'deal' and deal_fields.parent_id = deals.id
group by deals.id, deals.name
order by deals.id
Writing most of this is fairly straight forward. The problem I'm having is with the with properties as (...) block. I've tried something like:
DB::statement('WITH properties AS ( ... )')
->table('deals')
->select(' deals.*, json_agg(properties.*) as deal_properties, ')
...
->get();
But I notice the execution stop after DB::statement()
Is there a method in the Query Builder that I'm missing? How can I prefix my query with the WITH properties AS (...) statement?
I think it should also be noted that I'm trying to implement a Repository Pattern and I can't just wrap a DB::statement() around the whole query.
I've created a package for common table expressions: https://github.com/staudenmeir/laravel-cte
$query = 'select properties.*, [...]';
DB::table('deals')
->withExpression('properties', $query)
->leftJoin([...])
->[...]
You can also provide a query builder instance:
$query = DB::table('properties')
->select('properties.*', [...])
->leftJoin([...])
->[...]
DB::table('deals')
->withExpression('properties', $query)
->leftJoin([...])
->[...]
if you want some data fetch from a table you can use this type of code
$user = DB::table('table name')->where('name', 'John')->where('height','!>',"7")->select('table fields which you want to fetch')->get();
Or try using the larevel Eloquent ORM which will make things easier with the database.
for more example or reference
https://laravel.com/docs/5.0/queries
I think you can actually do this with eager loading,
assuming that the relationships are set up correctly.
(More reading here: https://laravel.com/docs/5.4/eloquent-relationships#constraining-eager-loads)
So I think you'd be able to add something like
->with(['properties' => function ($query) {
$query->select('field')
->leftJoin('join statement')
->groupBy('field1', 'field2');
}])

Select one column with where clause Eloquent

Im using Eloquent. But I'm having trouble understanding Eloquent syntax. I have been searching, and trying this cheat sheet: http://cheats.jesse-obrien.ca, but no luck.
How do i perform this SQL query?
SELECT user_id FROM notes WHERE note_id = 1
Thanks!
If you want a single record then use
Note::where('note_id','1')->first(['user_id']);
and for more than one record use
Note::where('note_id','1')->get(['user_id']);
If 'note_id' is the primary key on your model, you can simply use:
Note::find(1)->user_id
Otherwise, you can use any number of syntaxes:
Note::where('note_id', 1)->first()->user_id;
Note::select('user_id')->where('note_id', 1)->first();
Note::whereNoteId(1)->first();
// or get() will give you multiple results if there are multiple
Also note, in any of these examples, you can also just assign the entire object to a variable and just grab the user_id attribute when needed later.
$note = Note::find(1);
// $user_id = $note->user_id;

How to use 'IN (1,2,3)' with findAll?

I need to get a couple of Students from the database, and I have their primary keys in a comma-separated string.
Normally using SQL it would be something like:
$cleanedStudentIdStringList = "1,2,3,4";
SELECT * FROM Student WHERE id IN ($cleanedStudentIdStringList)
Yii's ActiveRecord seems to insert a single quote around bound parameters in the resulting SQL statement which cause the query to fail when using parameter binding.
This works, but doesn't use safe parameter binding.
$students = Student::model()->findAll("id IN ({$_POST['studentIds']})");
Is there a way to still use parameter binding and get only a couple of rows in a single query?
You can do it also that way:
$criteria = new CDbCriteria();
$criteria->addInCondition("id", array(1,2,3,4));
$result = Student::model()->findAll($criteria);
and use in array any values you need.
Aleksy
You can use findAllByAttributes method also:
$a=array(1,2,3,4);
$model = Student::model()->findAllByAttributes(array("id"=>$a));

Resources