Home > Database > Mysql Tutorial > How to Handle Binding Parameters in Laravel Raw DB Queries on Models?

How to Handle Binding Parameters in Laravel Raw DB Queries on Models?

Mary-Kate Olsen
Release: 2024-11-19 02:58:02
Original
414 people have browsed it

How to Handle Binding Parameters in Laravel Raw DB Queries on Models?

Binding Parameters in Laravel Raw DB Queries on Models

When working with raw DB queries in Laravel on models, binding parameters can be a challenge. This issue arises when using a combination of named and positional parameters, leading to the error "Invalid parameter number: mixed named and positional parameters."

To resolve this, consider the following solution:

  1. Replace the named parameters in the raw DB query with question marks (?).
  2. Use the setBindings() method to bind the parameter values to the query. The order of values in the array passed to setBindings() should match the order of the question marks in the query.
$property = Property::select(
    DB::raw("title, lat, lng, ( 
        3959 * acos( 
            cos( radians(  ?  ) ) *
            cos( radians( lat ) ) * 
            cos( radians( lng ) - radians(?) ) + 
            sin( radians(  ?  ) ) *
            sin( radians( lat ) ) 
        )
   ) AS distance")
)
->having("distance", "<", "?")
->orderBy("distance")
->take(20)
->setBindings([$lat, $lng, $lat, $radius])
->get();
Copy after login

By utilizing the setBindings() method, parameter values can be bound to the query, allowing for the execution of raw DB queries that require parameterization.

The above is the detailed content of How to Handle Binding Parameters in Laravel Raw DB Queries on Models?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template