我在Laravel 5.3中有一个DB::raw()
查询。
WHERE
条款之一是AND TIMESTAMPDIFF(YEAR, profiles.dob, CURDATE()) >= '$min_age'
。在这里,我正在检查用户的出生年份是否大于或等于某个数字(用户年龄)。
如果可能,如何在没有DB::table()
的情况下使用DB::raw()
重写此条款?
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"
));
这是简化版......
答案 0 :(得分:0)
查看您的查询,这应该是有效的:
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();