Home > Database > Mysql Tutorial > body text

How to Properly Bind Parameters in Complex Raw Queries in Laravel?

Susan Sarandon
Release: 2024-11-28 03:08:14
Original
954 people have browsed it

How to Properly Bind Parameters in Complex Raw Queries in Laravel?

Querying with Bindings: A Practical Solution in Laravel

When working with complex raw database queries in Laravel, binding parameters is crucial to prevent errors. This situation often arises when using a model-based approach.

Consider the following query encountered by a user:

$property = 
    Property::select(
        DB::raw("title, lat, lng, ( 
            3959 * acos( 
                cos( radians(:lat) ) * 
                cos( radians( lat ) ) * 
                cos( radians( lng ) - radians(:lng) ) + 
                sin( radians(:lat) ) * 
                sin( radians( lat ) ) 
            ) 
        ) AS distance", ["lat" => $lat, "lng" => $lng, "lat" => $lat])
    )
    ->having("distance", "<", $radius)
    ->orderBy("distance")
    ->take(20)
    ->get();
Copy after login

This query attempts to filter properties based on their distance from a given point using a raw SQL calculation. However, an error occurs because of mixed named and positional parameters.

To resolve this issue, one should leverage the setBindings method, which allows for explicitly specifying the query's bindings. Here's the modified and working code:

$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 using positional placeholders (?) in the raw SQL and invoking setBindings with the appropriate array of values, the query is executed properly, binding the parameters to the appropriate placeholders.

The above is the detailed content of How to Properly Bind Parameters in Complex Raw Queries in Laravel?. 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