Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use BETWEEN and AND in laravel

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'
like image 829
akkarthe Avatar asked Mar 04 '14 16:03

akkarthe


1 Answers

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)
like image 85
Quasdunk Avatar answered Oct 21 '22 04:10

Quasdunk