简体   繁体   中英

Rewrite DB::raw() query to simple DB::table()

I have a DB::raw() query in Laravel 5.3.

One of WHERE clauses is AND TIMESTAMPDIFF(YEAR, profiles.dob, CURDATE()) >= '$min_age' . Here I'm checking if user's year of birth is greater or equal to a certain number (user age).

How can I rewrite this clause using DB::table() without DB::raw() , if possible?

DB::select(
            DB::raw(
                "SELECT profiles.dob, profiles.city, profiles.id, users.username, photos.photo "
                . "FROM profiles INNER JOIN users ON profiles.id = users.id "
                    . "LEFT JOIN photos ON profiles.id = photos.profile_id "
                . "WHERE users.active = 1 "
                    . "AND profiles.income >= '$seekingIncome' "
                    . "AND profiles.religion IN ('$seekingReligion') "
                    . "AND TIMESTAMPDIFF(YEAR, profiles.dob, CURDATE()) >= '$min_age' "
                    . "AND TIMESTAMPDIFF(YEAR, profiles.dob, CURDATE()) <= '$max_age' "
                . "GROUP BY profiles.id"
        ));

This is simplified version...

Looking at your query, this should be work:

DB::table('profiles')
->select('profiles.dob', 'profiles.city', 'profiles.id', 'users.username', 'photos.photo')
->join('users','profiles.id','=','users.id')
->leftJoin('photos'.'profiles.id','=','photos.profile_id')
->where('users.active',1)
->where('profiles.income','>=',$seekingIncome)
->whereIn('profiles.religion', $seekingReligion)
->whereRaw('TIMESTAMPDIFF(YEAR, profiles.dob, CURDATE()) >= "?"',[$min_age])
->whereRaw('TIMESTAMPDIFF(YEAR, profiles.dob, CURDATE()) <= "?"',[$max_age])
->groupBy('profiles.id')
->get();

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-2024 STACKOOM.COM