简体   繁体   中英

Better way to write this query in order to convert it into laravel eloquent

I have prepared this query but unable to convert it to laravel eloquent. I need help to find out if there is a better way to write this query in order.

Below is the query

https://gist.github.com/thedesignerkumar/ef9062efb262ec9c128f4832af32d3e2

SELECT
    rooms.location,
    rooms.id,
    rooms.`name`,
    users.name,
    IF(
      (
        bookings.`status` = 'booked' AND(
          NOT(
            bookings.end_time <= '2017-05-30 12:00:00' OR bookings.start_time >= '2017-05-30 12:35:00'
            ) OR(
            bookings.recurring = 1 AND DATE(bookings.start_time) <= '2017-05-30' AND NOT(
              TIME(bookings.end_time) <= '12:00:00' OR TIME(bookings.start_time) >= '12:35:00'
              )
            )
            )
        ),
      'Booked',
      'Available'
      ) AS 'Status',
    bookings.recurring,
    bookings.start_time,
    bookings.end_time
    FROM
    rooms
    LEFT JOIN
    bookings
    ON
    rooms.id = bookings.room_id
    LEFT JOIN
    users
    ON
    bookings.user_id = users.id
    ORDER BY
    STATUS
    DESC
    ,
    bookings.start_time ASC,
    rooms.id ASC

Eloquent isn't the only method of querying a database in Laravel. Eloquent is just the ORM that comes with Laravel. Eloquent itself is built on the QueryBuilder class that also comes with Laravel.

You can certainly rebuild your query using the query builder but a more efficient method would be to user your existing query like so: DB::select($query) .

If you choose to just put your query directly into DB::select() rather than rebuilding it with the QueryBuilder you will be vulnerable to SQL injection attacks. You'll need to handle these prior to building the SQL query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM