Convert Query Builder to Eloquent - laravel

I have these tables:
products: id, name
orders: id, number
order_items: order_id, product_id
So I want to get best order products. And i make this code below.
$sales = DB::table('products')
->leftJoin('order_items','products.id','=','order_items.product_id')
->leftJoin('orders','orders.id','=','order_items.order_id')
->selectRaw('products.*, COALESCE(sum(orders.item_count),0) total')
->groupBy('products.id')
->orderBy('total','desc')
->take(6)
->get();
Please help me convert query above to eloquent. This work but I want to get products morphed images too.

Eloquent also support leftJoin, so you can do something like this:
$sales = Product::query()
->leftJoin('order_items','products.id','=','order_items.product_id')
->leftJoin('orders','orders.id','=','order_items.order_id')
->selectRaw('products.*, COALESCE(sum(orders.item_count),0) total')
->groupBy('products.id')
->orderBy('total','desc')
->take(6)
->get();
But if you mean you want to use eager load, please share your models and these relations first,

Assuming you created proper relationships in the Product model, would look something like this:
Product::with('order_items', 'orders')
->selectRaw('COALESCE(sum(orders.item_count),0) as total')
->orderByDesc('total')
->limit(6)
->get();

Related

Laravel Query Builder in Model

I would like to know if is it possible to work in a model using query builder to make a join between 4 tables, I don't know how to use eloquent with 4 tables
this is in controller
$kurikulum = DB::table('siakad.tb_01')
->select('siakad.tb_01.*', 'siakad.krs_jadwal_aktiv.*', 'siakad.mata_kuliah.*', 'siakad.kurikulum_item.*', )
->join('siakad.krs_jadwal_aktiv', 'siakad.tb_01.staf_id', '=', 'siakad.krs_jadwal_aktiv.kdds')
->join('siakad.mata_kuliah', 'siakad.krs_jadwal_aktiv.kdmk', '=', 'siakad.mata_kuliah.kode')
->join('siakad.kurikulum_item', 'siakad.mata_kuliah.id', '=', 'siakad.kurikulum_item.mata_kuliah_id')
->get();
Please try this:
$kurikulum = DB::table('tb_01')
->select('tb_01.*', 'krs_jadwal_aktiv.*', 'mata_kuliah.*', 'kurikulum_item.*')
->join('krs_jadwal_aktiv', 'tb_01.staf_id','krs_jadwal_aktiv.kdds')
->join('mata_kuliah', 'krs_jadwal_aktiv.kdmk','mata_kuliah.kode')
->join('kurikulum_item', 'mata_kuliah.id','kurikulum_item.mata_kuliah_id')
->get();

Product filtering problems with Laravel Query Builder

I try to implement ajax based filtering in my ecommerce project homepage for searching a product. I am using Laravel Query Builder. My Query for filtering products is given below-
$result= DB::table('products')
->leftjoin('products_description','products.products_id','products_description.products_id')
->leftjoin('image_categories', 'products.products_image', '=', 'image_categories.image_id')
->leftjoin('products_to_categories','products.products_id','products_to_categories.products_id')
->leftjoin('categories','products_to_categories.categories_id','categories.categories_id')
->when($category_slug, function($q) use ($category_slug) {
return $q->where('categories.categories_slug', $category_slug);
})
->where('products_name','like',"%{$querval}%")
->where('image_categories.image_type','=','ACTUAL')
->orderby('products.products_id','DESC')
->take(5)
->get();
I get every product twice in search result. don't know why. A sample response is given in this picture.
Can anyone help me to optimize my query for getting the desired result?
join with categories table only when you have to.
and select your columns strictly. then group by selected columns.
$result= DB::table('products')
->leftjoin('products_description','products.products_id','products_description.products_id')
->leftjoin('image_categories', 'products.products_image', '=', 'image_categories.image_id')
->when($category_slug, function($q) use ($category_slug) {
return $q->leftjoin('products_to_categories','products.products_id','products_to_categories.products_id')
->leftjoin('categories','products_to_categories.categories_id','categories.categories_id')
->where('categories.categories_slug', $category_slug);
})
->where('products_name','like',"%{$querval}%")
->where('image_categories.image_type','=','ACTUAL')
->orderby('products.products_id','DESC')
->select(['products_name','products.id','image_path'])
->groupBy(['products_name','products.id','image_path'])
->take(5)
->get();
you can use from groupBy to avoid comming repeated data.
try this one:
$result= DB::table('products')
->leftjoin('products_description','products.products_id','products_description.products_id')
->leftjoin('image_categories', 'products.products_image', '=', 'image_categories.image_id')
->when($category_slug, function($q) use ($category_slug) {
return $q->where('categories.categories_slug', $category_slug);
})
->where('products_name','like',"%{$querval}%")
->where('image_categories.image_type','=','ACTUAL')
->orderby('products.products_id','DESC')
->groupBy('products_name','products.products_id')
->take(5)
->get();

Laravel Query Builder left join

can someone please tell me, why i am not able to select section from sections table using left join. i want list of teachers in a table, i am able to access all data from teachers table, but i am not able to see sections using left join.
Teacher Table have section_id column, which should access data from sections table on section column.
right now it is giving error when i try to fetch data in view using {{$teacher->section}} Below is my code.
public function listteachers(Request $request)
{
$teachers = DB::table('teachers')
->select('teachers.*')
->leftjoin('sections', 'teachers.section_id', '=', 'sections.id')
->orderBy('pass_exp', 'ASC')
->get();
return view('teachers.list',compact('teachers'));
}
You need to select the columns you want from the sections table in your query.
For example:
$teachers = DB::table('teachers')
->select('teachers.*', DB::raw('sections.name as section_name'))
->leftJoin('sections', 'teachers.section_id', '=', 'sections.id')
->orderBy('pass_exp', 'ASC')
->get();
Change the code to the following
$teachers = DB::table('teachers')
->select('teachers.*','sections.name as section_name')
->leftJoin('sections', 'teachers.section_id', '=', 'sections.id')
->orderBy('pass_exp', 'ASC')
->get();

Finding a user with highest post created in last 24 hours, laravel Eloquent

How to find the user with the highest post created in the last 24 hours in laravel?
sorted by the number of posts in descending order.
If I'm not wrong, you are asking for the users with the highest number of posts created in the last 24 hrs.
To accomplish this, do the following:
$users = User::withCount(['posts' => function ($query) {
$query->where('created_at', '>=', carbon()->now()->subDay());
}])->orderBy('posts_count', 'DESC')
->get();
As the documentation states, you can add constraints to the queries.
Counting Related Models
If you want to count the number of results from a relationship without actually loading them you may use the
withCount method, which will place a {relation}_count column on
your resulting models. For example:
$posts = App\Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}
You may add the "counts" for multiple relations as well as add
constraints to the queries:
$posts = Post::withCount(['votes', 'comments' => function ($query) {
$query->where('content', 'like', 'foo%');
}])->get();
echo $posts[0]->votes_count;
echo $posts[0]->comments_count;
use Carbon\Carbon;
get user id:
$minusday = Carbon::now()->subDay();
$user_id = DB::table('posts')
->select('user_id', DB::raw('count(id) as total'))
->where('created_at', '>=', $minusday)
->groupBy('user_id')
->orderBy('total','desc')
->limit(1)
->get();
In regular SQL syntax you'd need something like below:
SELECT COUNT(id), user_id
FROM posts
WHERE created_at = today
GROUP BY user_id
ORDER BY COUNT(user_id) DESC
LIMIT 1;
It gets all the posts, groups them by user_id, sorts them with the highest user_id count up top and gets the first record.
I am by no means an expert on SQL, let alone the query builder in Laravel, so someone else would probably be better at writing that.
I know that you can get the posts that were created today by using Carbon, like so:
Post::whereDate('created_at', Carbon::today())->get();
EDIT: This might work for you:
$last24h = Carbon::now()->subDay();
DB::table('posts')
->select(array(DB::raw('COUNT(id)', 'user_id')))
->where('created_at', '>=', $last24h)
->groupBy('user_id')
->orderBy('COUNT(id)', 'DESC')
->limit(1)
->get();
Be sure to include use Carbon\Carbon to be able to use Carbon.
This should give you both the amount of posts and the corresponding user id.

Laravel elequent pivot table using where

How can I use Laravel to do something like this:
Tables:
projects:
id,name, active
pivot table: project_users
id, project_id, user_id
If I do this, I get good results, including all users of the project
Project::with('users')->where('active', '=', 1)->get();
But how can I filter on users and on active ? something like ?
Project::with('users')->where('active', '=', 1)->where('users',=,3)->get();
or ??
Project::with('users')->where('active', '=', 1)->where('users.user_id',=,3)->get();
If you want to restrict rows in the table you are eager loading then you can add constraints to the eager load where you can perform your usual QueryBuilder operations on the $query. So in your example we can do the following:
Project::with(['users' => function($query)
{
$query->where('user_id', '=', 3);
}])->where('active', '=', 1)->get();
This is assuming active is accessible to your initial table before the eager load.

Resources