Use custom function inside eloquent orderBy() method - php

I have a list or products in my database that needs to be ordered based on their updated_at field. But I also want to view the products at the beginning that are missing some attributes.
For example, I want to list those products at first that are missing description or colors and then order them based on their update date. Also I want to paginate them so I cannot sort them after I retrieve all the products from database.
So is there a way to achieve this using eloquent in Laravel?
This is how my products table looks like,
products
-id
-style
-title
-description
-colors
-sizes
-cost
-weight
-created_at
-updated_at

You can use limit and skip for pagination not sure but you can use like this for your problem..
function getProdcucts($skip, $limit){
$list = DB::table('reports')->select()
->where('colors', '=', null)
->orWhere('description', '=', null)
->orderBy('updated_at', 'desc')
->skip($skip)
->limit($limit)
->get();
return $list;
}
Dont fetch all record in one time, fetch record from db according to per page items.

Related

Join tables and see the count of categories in each category name in laravel 8

Excuse me want to ask. I'm sorry in advance if my language is not neat.
I have a category table with columns:
id (pk)
name
and others
I have a post table with columns:
id (pk)
category_id(fk)
and others
I want to count the number of posts from each category along with the category name in laravel 8.
This is my jQuery but it's incorrect:
$categ = DB::table('posts')
->select('category_id', 'categories.id', DB::raw('count(posts.id) as total_product'))
->join('categories', 'posts.category_id', '=', 'categories.id')
->groupBy('posts.category_id')
->get();
Can anyone help me?
If You are willing to use Eloquent, the answer would be much simple.
Post would be a model for posts table
Category would be a model for categories table
there would be one-to-one or any other relationship as per
requirements between models
Let's say there is a one-to-many relationship between Category and Post model
This can be achieved by adding a function in your Category model
public function posts()
{
return $this->hasMany(Post::class);
}
then you can use something like...
Category::withCount('posts')->get()
I assuming that you are using wrong table names in the query or may be have put the wrong table name in the question.
Let say your post table name is posts and categories table is categories, then your query should be:
$categ = DB::table('posts')
->select('categories.id', "categories.name", DB::raw("count(posts.id) as total_product"))
->join('categories, "posts.category_id', '=', 'categories.id')
->groupBy('posts.category_id')
->get();
Please note - Make sure to replace the table names with your tables.
If you are using this for one time load, then you can use the model relationship as well to get the complete information without creating a custom query.
https://laravel.com/docs/8.x/eloquent-relationships
You can have category to post relation.
Say you have Models Category and Post, then you can have below relation in Category model.
public function posts(){
return $this->hasMany(Post::class, 'category_id', 'id');
}
And then in your code you can use $category->posts to get collection of posts for the category and can use $category->posts->count() to get the count of posts for the category.

Wishlist system with Laravel and Spatie query builder

I need to create a wishlist with laravel, I already use spatie/query-builder to get products.
At this time everything works fine and I can retrieve products already added to wishlist.
I need help for reverse the process.
Three tables are used :
users
products
products_favorites (pivot table) with user_id and product_id
If record exists in pivot table product is in wishlist
So with this custom query builder filter :
return $query->join('product_favorites', function ($query) {
$query->on('product_favorites.product_id', '=', 'products.id');
})->where('product_favorites.user_id', '=', Auth::id());
I can get products who are in current user wishlist. I want to reverse the process.
Get all products who aren't in product_favorites table.
How do you think I can achieve this ?
Thank's for your help
I'm not sure but this on seems to work :
return $query->leftJoin('product_favorites', function ($query) {
$query->on('product_favorites.product_id', '=', 'products.id');
})->where('product_favorites.user_id', '=', null);

Laravel query many to Many

I need help.I have 2 tables products and categories:
Get request sends category id. My question is: how to build a query using the product model??? (The query looks like this: Output the product where the category id is equal to $ request-> category). Table connections are configured, I only need the query, (I read the documentation, but do not not understand it)
You can use:
$products = Product::whereHas('categories', function($q) use ($categoryId) {
$q->where('id', $categoryId);
})->get();
Read about querying relationships
Of course you need to have configured Product model with categories relationship.
You've said it's many-to-many relationship, all relations are configured and you want to use Product model to build a query. In this case, you should use the whereHas() method:
Product::whereHas('categories', function($q) use($request) {
$q->where('id', $request->category);
}))->get();

Getting all users that created an item today in Laravel

I want to make a list of all users that created an item.
These items have the row user_id
To get all items created today, I do this:
$items = Item::whereDay('created_at', '=', date('d'));
Now I want to perform a query that gives me all users who have created an item today. There will be users who created 1000 items, and there will be users that didn't do anything at all.
I could do this with ->unique() but there must surely be a better way to do this.
Any suggestions?
Assuming you have the items relationship set on your User model you could do something like:
$users = User::whereHas('items', function ($query) {
$query->where('created_at', '>=', \Carbon\Carbon::today());
})->get();

Retrieve results based on condition of relation laravel

How can I achieve the following with Laravel.
I have a table Products, which has a oneToMany relationship with ProductSizes - product sizes holds sizes related to a product.
I'm trying to do a query where - I get all products, where productSizes has a size of say 'Medium'.
I looked at using 'With' but this just returns an object with the overall product listing, with only those sizes....
I want to actually only bring back products that specifically only have a value of 'Medium' within the size column of the ProductSizes table.
$medium_product_ids = ProductSizes::where('size_name', '=', 'medium')->distinct()->get(array('product_id'));
$products = Products::whereIn('product_id',$medium_product_ids)->get();
Perhaps use a join:
Product::join('product_sizes', 'product_sizes.id', '=', 'products.product_size_id')
->where('size_name' = 'medium')
->get();
Using 'with' eager loads the relationship after the query has run so you can't constrain using it.
Try this, i think it should get products with only medium size:
Products::leftJoin('ProductSizes', 'products.id', '=', 'ProductSizes.product_id')
->groupBy('products.id')
->having(DB::raw('count(*) = 1 and size="Medium"'))
->get();

Categories