HI I am trying to use the following and not sure how to get this fixed
SELECT * FROM search_users
WHERE
match(first_name,last_name,country,city,location,nationality,short_bio)
against (?)
AND
search_users.loc_lng BETWEEN '-0.24272918701172' AND '-0.24272918701172'
AND
search_users.loc_lat BETWEEN '51.47026338272' AND '51.47026338272'
I am trying to write a laravel query that does exactly the same as
select * from search_users
where
......
and search_users.loc_lng BETWEEN '-0.24272918701172' AND '-0.24272918701172'
AND search_users.loc_lat BETWEEN '51.47026338272' AND '51.47026338272'
If you just want to build the query / get pure data without any logic around it, you can simply use the Query Builder:
$results = DB::table('search_users')
->where('first_name', $firstname)
->where('last_name', $last_name)
->where('country', $country) //and so on
->whereBetween('loc_lng', array(-0.24272918701172, -0.24272918701172))
->whereBetween('loc_lat', array(51.47026338272, 51.47026338272))
->get();
And sure enough you can use the same syntax if you're working with a Model:
$users = User::where('key1', $value1)
->where('key2', $value2)
->whereBetween('loc_lng', array(-0.24272918701172, -0.24272918701172))
->whereBetween('loc_lat', array(51.47026338272, 51.47026338272))
->get();
A little additional explanation concerning your question about how to use AND in eloquent:
AND is used by default if you use 2 or more where()s. So
DB::table('search_users')->where('first_name', $firstname)
->where('last_name', $last_name)
equals
SELECT * FROM search_users WHERE first_name = ? AND last_name = ?
For OR you can use orWhere():
DB::table('search_users')->where('first_name', $firstname)
->orWhere('last_name', $othername)
which equals
SELECT * FROM search_users WHERE first_name = ? OR first_name = ?
And sometimes you may need something more complicated, for instance:
SELECT * FROM search_users
WHERE first_name = ?
AND (last_name = ? OR last_name = ?)
AND age > 27
In Eloquent, this would be:
DB::table('search_users')
->where('first_name', $firstname)
->where(function($query) {
$query->where('last_name', $lastName1);
$query->orWhere('last_name', $lastName2);
})
->where('age', '>', 27)
Related
SELECT *
FROM table_name
WHERE
CONCAT(id,name, address) LIKE '%same_string%'
What is an alternate query for this in Laravel
Try this.
$field = ['name','id','address'];
$name = DB::Table('bookinfo')->Where(function ($query) use($string, $field) {
for ($i = 0; $i < count($field); $i++){
$query->orwhere($field, 'like', '%' . $string .'%');
}
})->get();
**
Laravel
- The general search in multiple columns the in single input
**
one of the user table in the first name, last name, job title column available and I have one input search in any value enter then find all column in associated data fetch and display
$searchQuery = trim($request->query('search'));
$requestData = ['firstname', 'lastname', 'job_title'];
$user = User::where(function($q) use($requestData, $searchQuery) {
foreach ($requestData as $field)
$q->orWhere($field, 'like', "%{$searchQuery}%");
})->get();
Try this for separate column
DB::table("table_name")->whereRaw(" (`id` like ? or `name` like ? or `address` like ? ) ",["%".$same_string."%","%".$same_string."%","%".$same_string."%"])->get();
I'm trying to use multiple where queries on a sqlite database which are then only selected between two date ssDate and seDate. for some reason, I am having nothing returned when I know there is an entry in between two dates.
if($status == "newOngoingClosed"){
//dd($status, $ssDate, $seDate);
$selStatus = Account::where('cActive', '=', 'New')
->orWhere('cActive', '=', 'Ongoing')
->orWhere('cActive', '=', 'Closed')
->whereBetween ('refDate', [$ssDate, $seDate])
->get();
dd($selStatus);
return view('reports_active')->withDetails($selStatus)->withQuery($status);
}
any help would be greatly appreciated.
Instead of using multiple orWhere you can use whereIn to get the desired output:
$selStatus = Account::whereIn('cActive', ['New','Ongoing','Closed'])
->whereBetween ('refDate', [$ssDate, $seDate])
->get();
Your query currently is:
select *
from `accounts`
where `cActive` = ? or `cActive` = ? or `cActive` = ? and `refDate` between ? and ?
Notice that the last condition is and AND which means it will select things which are either new or ongoing or closed and between those dates
You need:
Account::where([
['cActive', '=', 'New','or'] ,
[ 'cActive', '=', 'Ongoing','or' ],
['cActive', '=', 'Closed','or']
])->whereBetween ('refDate', [Carbon::now(), Carbon::now()])->get() //Note the carbons are just date placeholders , you can use your own
This will execute:
select * from `accounts` where (`cActive` = ? or `cActive` = ? or `cActive` = ?) and `refDate` between ? and ?
I've been trying to do a query in Laravel that in raw SQL will be like this
"SELECT * FROM students WHERE (((students.user_id)=$id) AND (((students.name) Like '%$q%') OR ((students.last_name) Like '%$q%') OR ((students.email) Like '%$q%')))")
I follow this thread (Eloquent WHERE LIKE clause with multiple columns) and it worked fine, but only with two columns Ej:
$students = student::where(user_id, Auth::id())
->whereRaw('concat(name," ",last_name) like ?', "%{$q}%")
->paginate(9);
But if I add more than two columns then the resultant variable is always empty, no matter if what is in the variable $q match with one or more columns:
$students = student::where(user_id, Auth::id())
->whereRaw('concat(name," ",last_name," ",email) like ?', "%{$q}%")
->paginate(9)
I am pretty sure I am missing something but i can't find what it is. Thanks in advance.
You can do something like this:
$students = student::where('user_id', Auth::id())->where(function($query) use ($q) {
$query->where('name', 'LIKE', '%'.$q.'%')
->orWhere('last_name', 'LIKE', '%'.$q.'%')
->orWhere('email', 'LIKE', '%'.$q.'%');
})->paginate(9);
The above Eloquent will output SQL similar to
"SELECT * FROM students WHERE students.user_id = $id AND (students.name like '%$q%' OR students.last_name Like '%$q%' OR students.email Like '%$q%')"
I use Laravel. As you know, Laravel doesn't support UNION clause for the query. So I have to write it as raw when I want to paging the whole results. Something like this:
$results = DB::select('SELECT id, title, description, imgPath
FROM news n
WHERE n.title LIKE %$q OR n.description LIKE %$q
UNION ALL
SELECT id, title, description, imgPath
FROM productions p
WHERE p.title LIKE %$q OR p.description LIKE %$q
');
As I said, I use Laravel, So how can I pass $q to the query in Laravel? All I'm trying to do is making the query safe against SQL injections. That's why I'm trying to pass the parameters to the query rather that using them directly in the query.
In pure PHP I can do that like this:
$st = $dbh->prepare('SELECT ... WHRER col LIKE %:q');
$st->bindParam(':q', $q, PDO::PARAM_INT);
I want something like this ^ in Laravel.
Yes, there is union: https://laravel.com/docs/5.3/queries#unions
I didn't test it out, but it should looks something like this:
$first = DB::table('news')
->select(['id', 'title', 'description', 'imgPath'])
->where(function($query) use ($q) {
$query->where('title', 'like', "%$q")
->orWhere('description', 'like', "%$q");
});
$result = DB::table('productions')
->select(['id', 'title', 'description', 'imgPath'])
->where(function($query) use ($q) {
$query->where('title', 'like', "%$q")
->orWhere('description', 'like', "%$q");
})
->unionAll($first)
->get();
NOTE:
With union you won't be able to do paginate out of the box. You will need to create the paginator object by yourself as shown here: Laravel - Union + Paginate at the same time?
Your "pure PHP code" won't work either. You have to respect SQL and PDO syntax
$st = $dbh->prepare('SELECT ... WHRER col LIKE :q');
$st->bindParam(':q', "%$q");
will do.
The same with Laravel: you have to define a placeholder in the query and then send it as a parameter
$sql = 'SELECT * FROM news WHERE title LIKE :q OR description LIKE :q';
$results = DB::select($sql, ['q' => "%$q"]);
I'm trying to run a query through the ORM like this:
SELECT * from table where (fname like 'string%' or lname like 'string%')
AND (fname like 'string2%' or lname like 'string2%');
Here's what i have so far:
$results = ORM::factory('profiles');
foreach ($strings as $string) {
$result->where('fname', 'like', "$string%");
$result->or_where('lname', 'like', "$string%");
}
But this doesn't account for the parentheses. Any ideas?
Found the answer.
It's done with Kohana's where_open() and where_close() methods.
It works fine for me .
ORM code sample
$musicslist = ORM::factory('user_music')
->where_open()
->where('title', 'like', '%' . $search . '%')
->or_where('album', 'like', '%' . $search . '%')
->or_where('artist', 'like', '%' . $search . '%')
->where_close()
->and_where('app_userid','=', $userid)
->find_all();
it will create SQL query
SELECT `user_musics`.* FROM `user_musics` WHERE (`title` LIKE '%as%' OR `album` LIKE '%as%' OR `artist` LIKE '%as%') AND `app_userid` = '21'
Couldn't get code formatting to work in the comment - just thought I'd add a simple example to the answer in case anyone else comes across it:
$query = DB::select()
->from('some_table')
->where_open()
->where('column_one', '=', 1)
->or_where('column_two', '=', 2)
->where_close();
would produce the following SQL:
SELECT * FROM some_table
WHERE (column_one = 1 OR column_two = 2);