i want to search users by fullname so i need to concat two columns which are first_name and last_name and look if it matches the given value or not, this is my try
$users = User::where(function($usersSearchQuery) use ($user,$fullName){
$usersSearchQuery
->whereNotIn('id', $user->blockerUsers->pluck('blocked_id'))
->whereNotIn('id', $user->blockedUsers->pluck('blocker_id'))
->whereRaw('CONCAT(first_name," ",last_name) LIKE \''.$fullName.'\'%'); })->get();
i have an error in this line
->whereRaw('CONCAT(first_name," ",last_name) LIKE \''.$fullName.'\'%');
message: "SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')' at line 1 (SQL: select * from users where (1 = 1 and 1 = 1 and CONCAT(first_name," ",last_name) LIKE 'BertHue'%))"
Try this:
$users = User::where(function($usersSearchQuery) use ($user,$fullName){
$usersSearchQuery->whereNotIn('id', $user->blockerUsers->pluck('blocked_id'))
->whereNotIn('id', $user->blockedUsers->pluck('blocker_id'))
->whereRaw('CONCAT(first_name," ",last_name) LIKE \''.$fullName.'%\'');
})->get();
I replaced your last where with a whereRaw which allows you to use raw SQL.
Related
I am trying to exchange db::select() with db::table() so I can use pagination but since I have in my query sum() and am getting an error.
My Quest: How to use sum() and order results with Query Builder::table?
My old but working attempt
$query = 'SELECT SUM(votes.votes) AS c, sites.id, sites.user_id, sites.url, sites.type_id, sites.img_src, sites.details, sites.created_at, sites.updated_at
FROM sites
JOIN votes
WHERE sites.id = votes.site_id
GROUP BY sites.id, sites.user_id, sites.url ,sites.type_id, sites.img_src, sites.details, sites.created_at, sites.updated_at
ORDER BY c DESC LIMIT 10');
My new attempt
$test = DB::table('sites')
->join('votes', 'site.id', '=', 'votes.site_id')
->select(\DB::raw('SUM(votes.votes) AS c'), 'sites.id', 'sites.user_id', 'sites.url', 'sites.type_id', 'sites.img_src', 'sites.details', 'sites.created_at', 'sites.updated_at')
->where('sites.id ', '=', 'votes.site_id')
->groupBy('sites.id, sites.user_id, sites.url ,sites.type_id, sites.img_src, sites.details, sites.created_at, sites.updated_at')
->orderBy('c', 'DESC')
->get();
Error
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '.`url ,sites`.`type_id, sites`.`img_src, sites`.`details, sites`.`created_at, si' at line 1 (SQL: select SUM(votes.votes) AS c, `sites`.`id`, `sites`.`user_id`, `sites`.`url`, `sites`.`type_id`, `sites`.`img_src`, `sites`.`details`, `sites`.`created_at`, `sites`.`updated_at` from `sites` inner join `votes` on `site`.`id` = `votes`.`site_id` group by `sites`.`id, sites`.`user_id, sites`.`url ,sites`.`type_id, sites`.`img_src, sites`.`details, sites`.`created_at, sites`.`updated_at` order by `c` desc) ```
Group by multiple fields
You need to split the string in groupBy method, or Laravel will take it as one field:
->groupBy('sites.id', 'sites.user_id', 'sites.url' ,'sites.type_id', 'sites.img_src', 'sites.details', 'sites.created_at', 'sites.updated_at')
Compare two columns by whereColumn
->where('sites.id ', '=', 'votes.site_id')
will compare the column sites.id with string "votes.site_id", you need to use whereColumn to compare two columns:
->whereColumn('sites.id ', '=', 'votes.site_id')
I am using Laravel 5.5 and I have translated the following query:
'SELECT *
FROM instruments
LEFT join financials on instruments.id=financials.instruments_id
WHERE financials.id IN
( SELECT MAX(financials.id)
FROM financials
GROUP BY financials.instruments_id )
ORDER BY instruments.id ASC'
into eloquent:
$overviewArray = DB::table('instruments')
->leftJoin('financials', 'instruments.id', '=', 'financials.instruments_id')
->whereIn('financials.id', DB::raw('SELECT MAX(financials.id)
FROM financials
GROUP BY financials.instruments_id )
ORDER BY instruments.id ASC'))->get()->toArray();
However, I get the following error:
In Grammar.php line 135:
Type error: Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, object given, called
in C:\Users\admin\Desktop\Coding Projects\laravel_project\vendor\laravel\framework\src\Illuminate\Database\Query\Gramm
ars\Grammar.php on line 250
My guess is that my eloquent query is wrong? Any suggestions what is wrong with it?
I appreciate your replies!
$overviewArray = DB::table('instruments')
->leftJoin('financials', 'instruments.id', '=', inancials.instruments_id')
->whereIn('financials.id', function($query){
$query->select(DB::raw('MAX(financials.id)'))->
from('financials')->
groupBy('financials.instruments_id');})
->orderBy('instruments.id')
->get()
->toArray();
I guess it will be ok.
In my case it was because I was doing Event::get(44) instead of Event::find(44).
This is the native sql:
$sql = "Select count(name) from users Where email = 't#t.com' and user_id = 10";
I have this laravel code:
$checker = Customer::whereEmailAndUserId("t#t.com",10)->count("name");
Is this a correct way to do it in laravel?
You have to use where helper function and pass an array of checks. For example in your code it will be:
$checker = Customer::where([
['email', '=', 't#t.com'],
['user_id' '=', '10']
])->count();
Note: Please use the appropriate column name as it in table.
Assuming Customer model represents table users, you'll get query with eloquent like this:
Customer::where('email', 't#t.com')->where('user_id', 10)->select(\DB::raw('count(name)'))->get();
The option you are trying is incorrect
here is the right option
$users = \App\Customer::where('email','t#t.com')
->where('user_id',10)
->count()
Explanation of above code
App\Customer is the Model class and I am trying to read records where email = 't#t.com you can use various comparison operators like <,> and so on and you can also use the same function to for string pattern matching also
Eg.
$users = \App\Customer::where('email','%t.com')
->where('user_id',10)
->count()
You can use the same where function for Null Value test also
Eg.
$users = \App\Customer::where('email','=', null)
->where('user_id',10)
->count()
The above where clause will be converted to is null test of the SQL
You can read more here
Please I am trying to run a query that looks like this in raw sql
SELECT `qnty`, COUNT(*) FROM cartlist GROUP BY `pro_id`,`cart_id`,`price`
in laravel.
I have tried this
$count = DB::table('cartlist')
->select(DB::raw('count(*) as qnty'))
->where('pro_id', '$tt->pro_id')
->where('cart_id', '$cart_id')
->groupBy('pro_id','price')
->get();
But it gives the following error
Object of class Illuminate\Support\Collection could not be converted to int
$count = DB::table('cartlist') ->select(DB::raw('count(*) as qnty'))
->where('pro_id', '$tt->pro_id')
->where('cart_id', '$cart_id')
->groupBy('pro_id','price','cart_id') ->get();
I'm trying to do this:
SELECT
userId, count(userId) as counter
FROM
quicklink
GROUP BY
userId
HAVING
count(*) >= 3'
In doctrine with the querybuilder, I've got this:
$query = $this->createQueryBuilder('q')
->select('userId, count(userId) as counter')
->groupby('userId')
->having('counter >= 3')
->getQuery();
return $query->getResult();
Which gives me this error:
[Semantical Error] line 0, col 103 near 'HAVING count(*)': Error: Cannot group by undefined identification variable.
Really struggling with doctrine. :(
Your SQL is valid, Your query builder statement is invalid
All cause db will execute that query in following order:
1. FROM $query = $this->createQueryBuilder('q')
2. GROUP BY ->groupby('userId') // GROUP BY
3. HAVING ->having('counter >= 3')
4. SELECT ->select('userId, count(userId) as counter')
So as You can see counter is defined after its use in having.
Its SQL Quirk. You can not use definitions from select in where or having statements.
So correct code:
$query = $this->createQueryBuilder('q')
->select('userId, count(userId) as counter')
->groupby('userId')
->having('count(userId) >= 3')
->getQuery();
return $query->getResult();
Do note repetition in having from select
I am going to answer for people who still have this type of error.
First things first, you seem to have translated a native sql query inside a query builder object. More so, you have named your object as q
$query = $this->createQueryBuilder('q');
What this means, in general, is that every condition or grouping etc you have in your logic should address fields of q: q.userId, q.gender, ...
So, if you had written your code like below, you would have avoided your error:
$query = $this->createQueryBuilder('q')
->select('q.userId, count(q.userId) as counter')
->groupby('q.userId')
->having('counter >= 3')
->getQuery();
return $query->getResult();
I think you are missing the 'from' statement
$query = "t, count(t.userId) as counter FROM YourBundle:Table t group by t.userId having counter >1 ";
return $this->getEntityManager()->createQuery($query)->getResult();
This should work. You can even do left joins or apply where clausules.
you can define HAVING parameter via setParameter() method as well
$qb->groupBy('userId');
$qb->having('COUNT(*) = :some_count');
$qb->setParameter('some_count', 3);