当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Laravel 4.2 Query Builder Not working Perfectly

问题描述:

My DB is like this

I have a Laravel 4.2 Query Builder Code

 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

//Basic Parts

->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()')

//Ordering

->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();

echo $query->count();

$info = $query->get();

Here if I want to know what query is executed I have used this code

$info = $query->get();

$queries = DB::getQueryLog();

Now I get This output

0{"query":"select distinct `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` from `car` , `available_car`, `users` where `available_car`.`car_id` = ? and `available_car`.`is_sold` = ? 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","bindings":["`car`.`car_id`","no"],"time":1.03}

If I run this output code in PHP MyAdmin Query

SELECT DISTINCT `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`

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

I have Output like this

So, I get empty row in Laravel and get 8 row in raw query for the same SQL query.

Can anyone help me to solve this problem?

Thanks in advance for helping.

网友答案:

You can use binding.

Or you can use Joining.

网友答案:

As far as i know, you can not bind table and column names

that's why your query is failing (more accurately, not giving the desired result).

"bindings":["`car`.`car_id`","no"]

here you are binding car.car_id

it won't work. following should work.

->whereRaw('`available_car`.`car_id` =`car`.`car_id`')

this should give the same result as phpmyadmin.

分享给朋友:
您可能感兴趣的文章:
随机阅读: