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
Related
I am using Laravel 5.6 and i have a standard query
Order::where('dict_statuses_id', 1)
->leftJoin('dict_statuses', 'dict_statuses_id', '=', 'dict_statuses.id')
->get();
So i have list of orders with details where status = 1 (new) after join table i see status as New or Complete. Is any way to change this query using whereHas ?
i tried use
Order::whereHas('status', function($q){
$q->where('dict_statuses_id', 1);
})->get();
But no results, in model Order i have
public function status()
{
return $this->hasMany('App\DictStatuses');
}
[Updated]
i have an error:
Column not found: 1054 Unknown column 'dict_statuses.orders_id'
in 'where clause' (SQL: select * from `orders` where exists
(select * from `dict_statuses` where `orders`.`id` = `dict_statuses`.`orders_id` and `dict_statuses_id` = 1)
and `orders`.`deleted_at` is null)
In my table i have table Orders where is field: dict_statuses_id
and table dict_statuses with fields: id, public_name
Why error is about dict_statuses.orders_id
Try Order::has('status')->get();
You can pass in variables to a relationship so you could potentially do.
public function status($id) {
return $this->hasMany(DictStatuses::class)->where('dict_statuses_id', $id);
}
Try defining the local key & foreign key.
$this->hasMany(DictStatuses::class, 'foreign_key', 'local_key');
I think your dict_statuses doesn't have a column called order_id.
Please include that column in your migration
then call
Order::whereHas('status', function($q){
$q->where('dict_statuses_id', 1);
})->get();
in your controller
or change the relation in Order model as
public function status(){
return $this->belongsTo('App\DictStatuses'):
}
I have 2 tables.
Products
Brands
Im trying to return top 10 brand models with the most products.
I've tried.
Product::select('brand', DB::raw('count(brand) as count'))->groupBy('brand')->orderBy('count','desc')->take(10)->get();
But that doesn't return the hole model and only returns
Brand
Count
I've also tried
return $brands = Brand::whereHas('products', function($q) {
$q->count() > 10;
})->get();
But I get the error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'brands.id' in
'where clause' (SQL: select count(*) as aggregate from products
where brands.id = products.brand)
My Brand Model
public function products()
{
return $this->hasMany('App\Product','brand');
}
My Product Model
public function manuf()
{
return $this->belongsTo('App\Brand','brand');
}
try this:
$brands = Brands::has('products', '>' , 10)->with('products')->get();
You should be able to accomplish this with the withCount method if you're using at least Laravel 5.3:
Brand::withCount('products')->orderBy('products_count', 'DESC')->take(10)->get();
Where products is the name of your relation. This will give you a new field in your query, products_count that you can order by.
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
I have the three Models Post, Page and Category.
Each Page is assigned to one Category and each Post is assigned to one Page.
I have already defined the relationships in the models. What I want to do now is to use Eloquent ORM to get all Post-objects that are from a Page with a certain Category. So basically, in SQL I would need to do it like this
select p.* from posts p INNER JOIN pages pa ON pa.id = p.page_id where p.created_time > '2015-08-18 00:00:00' and pa.categories_id = 1 and p.isVisible = 1 order by p.total_count desc limit 100
I'm now somehow trying to do the same with Eloquent, but I'm stuck. My current code looks like this
// Getting all the top posts from facebook for today.
/** #var Builder $topPosts */
$topPosts = Post::where('created_time', '>', Carbon::today()->toDateTimeString());
if ($type !== null) {
$topPosts = $topPosts->where('type', $type);
}
return $topPosts->orderBy('total_count', 'desc')
->visible()
->take($limit)
->get();
Now, I wanted to add the category, but I don't know how to do it. I tried these steps here:
$topPosts = $topPosts->with(['page' => function($query) use($categoryId){
$query->where('page_categories_id', $categoryId);
}]);
and this one
$topPosts = $topPosts->with('page')->where('page_categories_id', $categoryId);
but none of them worked. How would I achieve that? I always get the error message
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories_id' in 'where clause' (SQL: select * from posts where created_time > 2015-08-18 00:00:00 and categories_id = 1 and isVisible = 1 order by total_count desc limit 100)
It looks like you need to use whereHas() in place your with() statement there (http://laravel.com/docs/4.2/eloquent#querying-relations)
This should work, and is basically just querying Posts with associated Pages with the particular category_id. I haven't included your ordering and things..
$posts = Post::where('created_time', '>', Carbon::today()) // Eloquent shouldn't actually need the toDateTimeString()
->with('page') // leave this in to eager load the page
->whereHas('page', function($query) use ($categoryId) {
$query->where('page_categories_id', $categoryId);
})
->get();
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();