How do I use BETWEEN and AND in laravel

前端 未结 1 805
轻奢々
轻奢々 2021-02-14 13:09

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,na         


        
1条回答
  •  礼貌的吻别
    2021-02-14 13:40

    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)
    

    0 讨论(0)
提交回复
热议问题