Laravel 3 - Order by the division of two fields - php

I need following SQL converted to eloquent
select * from medias order by likes/views DESC, views ASC
I need to use paginate on the result, that is why i prefer eloquent.
Some of my other SQL queries are
$media_list = Media::order_by('likes', 'desc')->paginate($per_page);
I tried
$media_list = Media::order_by('likes/views', 'desc')->paginate($per_page);
But it gives error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'likes/views' in 'order clause'
SQL: SELECT * FROM `medias` ORDER BY `likes/views` DESC LIMIT 20 OFFSET 0
Anyone know how to fix this ?

Try , instead of /
$media_list = Media::order_by('likes,views', 'desc')->paginate($per_page);
or
$media_list = Media::order_by('likes`,`views', 'desc')->paginate($per_page);
And also this is the standard way of doing in laravel
$media_list = Media::order_by('likes', 'desc')->orderBy('views', 'desc')->paginate($per_page);
$media_list = DB::table('medias')
->select(DB::raw('(likes/views) AS resultant'))
->order_by('resultant', 'desc')->orderBy('views', 'desc')
->get();

Related

YEAR(begin_date) unknown column in laravel

SELECT COUNT(*) as count, MONTH(begin_date)
FROM `events`
WHERE (YEAR(begin_date) = YEAR(CURDATE()))
OR (YEAR(begin_date) = YEAR(CURDATE()) + 1)
GROUP BY MONTH(begin_date)
Here is sql query, i want to write it in laravel eloquent.
what i try:
$oncoming_events = DB::table('events')
->select(DB::raw('count(*) as numOfOncomingEvents, MONTH(begin_date)'))
->where('YEAR(begin_date)', '=', 'YEAR(CURDATE())')
->orWhere('YEAR(begin_date)', '=', 'YEAR(CURDATE()) +1')
->groupBy('MONTH(begin_date)')->get();
Error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'YEAR(begin_date)' in 'where clause' (SQL: select count(*) as numOfOncomingEvents, MONTH(begin_date) from events where YEAR(begin_date) =
laravel 5.6
btw
sql query works..
You need to use DB::raw() in where to tell the query builder that it is not column name it is data manipulation in query,
$oncoming_events = DB::table('events')->select(DB::raw('count(*) as numOfOncomingEvents, MONTH(begin_date)'))->where(DB::raw('YEAR(begin_date)'), '=', 'YEAR(CURDATE())')->orWhere(DB::raw('YEAR(begin_date)'), '=', 'YEAR(CURDATE()) +1')->groupBy(DB::raw('MONTH(begin_date)'))->get();

Use number in where condition in Laravel Query

The below query works well in mysql but how to represent the same thing using Laravel.
select * from user_subscription where vendor_id = 'user_100'
and 0 = (select count(*) from user_restricted_dates where vendor_id = 'user_100')
I tried with code but gives error as unknown column '0' in where clause
$list = UserSubscription::where('vendor_id', '=', $vendor_obj->vendor_id)
->where(0, '=', "(select count(*) from user_restricted_dates where vendor_id = 'user_100'")
->get();
Well the error indicates what it is but how to represent it
The where method of the Query Builder maps the first value you pass to a field in the model. You'd have to use the whereRaw method instead.
$list = UserSubscription::where('vendor_id', '=', $vendor_obj->vendor_id)
->whereRaw("0 = (select count(*) from user_restricted_dates where vendor_id = 'user_100')")
->get();

Laravel Eloquent whereHas error unknown column

I am trying to get the lowest price of a product to an item.
$items=Item::whereHas('products', function($query){
$query->orderBy('price','asc')->first();
})->with('page')->get();
Model Item.php
public function products(){
return $this->hasMany('App\Product','item_id','id');
}
ERROR
Column not found: 1054 Unknown column 'items.id' in 'where clause' (SQL: select * from products where products.item_id = items.id order by price asc limit 1)
Try the following:
DB::select(DB::raw("select * from products where products.item_id = items.id order by price asc limit 1"));
I looked up Laravel Eloquent documentation and changed code a little bit and now it works.
$items=Item::with(['products' => function($query){
$query->orderBy('price','asc')->first();
},'page'])->get();
https://laravel.com/docs/5.3/eloquent-relationships

Order by the difference of two columns in Laravel 5.3

I have an eloquent query where one of the orderBy is the difference of two columns.
$mymodel = Level::where([['ColA', 5], ['ColB', 10], ['ColC', 7]])
->orderBy('ColA', 'Desc')
->orderBy('ColA' - 'ColB', 'Desc')
->orderBy('ColC', 'Desc')
->orderBy('ColD', 'Asc')
->pluck('userId')->toArray();
The exact same code on localhost with sqlite works without an error. But on production with MySQL has the following error
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'order clause' (SQL: select `userId` from `levels` where (`ColA` = 5 and `ColB` = 10 and `ColC` = 7) order by `ColA` desc, `0` desc, `ColC` desc, `ColD` asc)
$model = Level::where($wheres)
->orderByRaw('(ColA - ColB) DESC')
->pluck('userId')
->toArray();

Laravel on sorting related model?

I know from laravel documentation that I can do eager loading like:
$records = (new Route)->with('country')->get();
But when I execute this:
$records = (new Route)->query()->with('country')->orderBy('country.name', 'asc')->paginate();
I get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'country.name' in 'order clause' (SQL: select * from `routes` order by `country`.`name` asc limit 2 offset 0)
How I can sort on related model ?
How can I force laravel to load joined tables?
I find the solution:
$records = (new Route)->query()->join('countries', 'routes.country_id', '=', 'countries.id');
But is not ideal because joining are performed manualy.
You can do the following with eager loading :
$records = (new Route)->with(['country' => function ($q) {
$q->orderBy('name', 'asc');
}])->get(); // or paginate or whatever

Categories