我的MySQL查询
SELECT DISTINCT `car`.`car_maker` as `brand`, `car`.`car_model` AS `model`, `available_car`.`car_price` AS `price`, `car`.`car_production_year` AS `year`, `available_car`.`car_id` AS `car_id`,`available_car`.`id` AS `id`, `available_car`.`current_position` AS `current_position`
FROM `car`, `available_car`, `users`
WHERE `available_car`.`car_id`=`car`.`car_id`
AND `available_car`.`is_sold` = 'no'
AND `available_car`.`created_at` BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
ORDER BY WEEK(`available_car`.`created_at`) DESC,
`available_car`.`car_price`DESC,
`users`.`last_paid_date` DESC,
`available_car`.`created_at` DESC
如何使用Laravel Query构建器进行转换?
我想让它像这种类型的查询 -
$info = DB::table('car` , `available_car`, `users')
->select('car.car_maker', 'car.car_model', 'available_car.car_price', 'car.car_production_year', 'available_car.car_id','available_car.id', 'available_car.current_position')
->get();
但它没有用。
我的数据库就像这样
有人可以帮我吗?
答案 0 :(得分:1)
尝试此查询:
DB::table('car')
->join('available_car', 'car.car_id', '=', 'availabe_car.car_id')
->join('users', 'available_car.user_id', '=', 'users.id')
->where('available_car.is_sold', 'no')
->whereRaw('available_car.created_at BETWEEN NOW() - INTERVAL 30 DAY AND NOW()')
->orderByRaw('WEEK(`available_car`.`created_at`) DESC')
->orderBy('available_car.car_price', 'desc')
->orderBy('users.last_paid_date', 'desc')
->orderBy('available_car.created_at', 'desc')
->select('car.car_maker as brand', 'car.car_model as model', 'available_car.car_price as price', 'car.car_production_year as year', 'available_car.car_id as car_id', 'available_car.id as id', 'available_car.current_position as current_position')
->distinct()->get()
请注意,这是未经测试的代码。
答案 1 :(得分:1)
您无法将多个表格传递给select
,因为它们将作为整体进行转义。作为使用内部联接的@ lukasgeiter解决方案的替代方案,您可以在DB::raw
内使用table()
:
DB::table(DB::raw('`car` , `available_car`, `users`'))
->select('car.car_maker', 'car.car_model', 'available_car.car_price', 'car.car_production_year', 'available_car.car_id', 'available_car.id', 'available_car.current_position')
->where('available_car.car_id', '`car`.`car_id`')
->where('available_car.is_sold', 'no')
->whereRaw('`available_car`.`created_at` BETWEEN NOW() - INTERVAL 30 DAY AND NOW()')
->orderByRaw('WEEK(`available_car`.`created_at`) DESC')
->orderBy('available_car.car_price', 'desc')
->orderBy('users.last_paid_date', 'desc')
->orderBy('available_car.created_at', 'desc')
->distinct()
->get();