Convert Mysql query to Laravel elequent - mysql

I trying to convert MySQL query to Laravel eloquent, but not getting the right output.
MySQL query -
Select contents.con_type, contents.operation, contents.ecu, contents.ecu_sub, COUNT(*)
from contents
group by operation, con_type, ecu, ecu_sub
order by operation asc, con_type asc
MySQL query to Laravel elequent -
$content = Content::query();
if ($request->input('total') == '1') {
$content = $content->select('con_type', 'operation', 'ecu', 'ecu_sub')
->groupBy('operation', 'con_type', 'ecu', 'ecu_sub')
->orderBy('operation', 'asc')
->orderBy('con_type', 'asc')
->get()->count();
}
The output I trying to get:
Thanks in advance.

Test
$content = Content::query();
if ($request->input('total') == '1') {
$content = $content->select(DB::raw('con_type, operation, ecu, ecu_sub, count(*) as `count`')
->groupBy('operation', 'con_type', 'ecu', 'ecu_sub')
->orderBy('operation', 'asc')
->orderBy('con_type', 'asc')
->get();
}

Related

How to optimize a laravel query, to find the average from another joined table

My query (DB::raw(AVG('pt.progress'))) this part is throwing error at the moment
$query = DB::table('projects as p')
->leftJoin('projects_tasks as pt','pt.project_id', 'p.id')
->select(
'p.id', 'p.project_name', DB::raw(AVG('pt.progress')) //this is where I need the average
);
$query->orderBy($order, $dir);
if ($limit != -1) {
$query->skip($start)->take($limit);
}
$records = $query->get();
Table structure:
projects:
========
id
project_name
...
...
projects_tasks:
===============
id
project_id,
parent, //0 or 1
progress //exmaple value 0.00 to 1.00
How to get the average of progress, where parent_id = 0 and project_id is the same?
The following query does work if I create a function and pass it in a loop, however, I want to optimize it and run it by joining on above query.
$data_row = DB::table('projects_tasks')
->select(DB::raw('(SUM(progress)*100)/count(progress) as project_progress'))
->where(['project_id' => $project_id, 'parent' => 0])
->get();
Seems that you have a syntax error on your query, the problem is in here DB::raw(AVG('pt.progress')).
Since you're using a raw query, the parameter there should be a string, so you must enclose that in quotes / double qoute.
$query = DB::table('projects as p')
->leftJoin('projects_tasks as pt','pt.project_id', 'p.id')
->select(
'p.id', 'p.project_name', DB::raw("AVG('pt.progress')")
);
$query->orderBy($order, $dir);
if ($limit != -1) {
$query->skip($start)->take($limit);
}
$records = $query->get();

Multiple operations in same column on Laravel Eloquent?

I have MySql Query :
select * from transactions where request_shipping_date = '2020-11-25' and status = 'paid' or 'on_process' or 'finish';
and I got 44 Rows
and I Want Convert to Eloquent Model :
$request_shipping_date = Carbon::now()->addDays(1)->format('Y-m-d');
$data = Order::with('order_details')
->where('request_shipping_date', 'like', $request_shipping_date.'%')
->Where('status', 'paid')
->orWhere('status', 'on_process')
->orWhere('status', 'finish')
->get();
and i got : 24025 Rows
Is there any wrong ?
The no of rows retrieved changes because of the like operator when comparing dates
Try using the below
$request_shipping_date = Carbon::now()->addDays(1)->format('Y-m-d');
$data = Order::with('order_details')
->whereDate('request_shipping_date', $request_shipping_date)
->Where('status', 'paid')
->orWhere('status', 'on_process')
->orWhere('status', 'finish')
->get();
You could also rephrase the eloquent query as
$request_shipping_date = Carbon::now()->addDays(1)->format('Y-m-d');
$data = Order::with('order_details')
->whereDate('request_shipping_date', $request_shipping_date)
->whereIn('status', ['paid', 'on_process', 'finish'])
->get();

Convert Raw SQL query to Laravel DB Query

I have the following raw SQL query:
select a.id user_id, a.email_address, a.name_first, a.name_last, count(b.id) number_of_videos, sum(b.vimeo_duration) total_duration, sum(b.count_watched) total_playbacks
from users a,
videos b
where a.id = b.tutor_id
and a.email_address in ('candace_rennie#yahoo.com', 'tjm#hiltoncollege.com', 'matthewjameshenshall#gmail.com', 'nkululeko#syafunda.co.za', 'khulile#syafunda.co.za', 'nzakheni#syafunda.co.za')
group by a.id;
This correctly gets 6 rows from the database. I'm trying to convert this to a Laravel database query like so:
$totals = DB::table('users')
->select(DB::Raw('users.id as user_id'), 'users.email_address', 'users.name_first', 'users.name_last', DB::Raw('count(videos.id) as number_of_videos'), DB::Raw('sum(videos.vimeo_duration) as total_duration'), DB::Raw('sum(videos.count_watched) as total_playbacks'))
->join('videos', 'users.id', '=', 'videos.tutor_id')
->where('users.id', 'videos.tutor_id')
->whereIn('users.email_address', array('candace_rennie#yahoo.com', 'tjm#hiltoncollege.com', 'matthewjameshenshall#gmail.com', 'nkululeko#syafunda.co.za', 'khulile#syafunda.co.za', 'nzakheni#syafunda.co.za'))
->groupBy('users.id')
->get();
This however return 0 rows. Is there anything I'm missing?
It should be smth like below even tho groupBy user id does not help much as id is unique.
$aggregates = [
DB::raw('count(b.id) as number_of_videos'),
DB::raw('sum(b.vimeo_duration) as total_duration'),
DB::raw('sum(b.count_watched) as total_playbacks'),
];
$simpleSelects = ['users.email_address', users.id, 'users.name_first', 'users.name_last'];
$emails = ['candace_rennie#yahoo.com', 'tjm#hiltoncollege.com'....]
$users = Users::select(array_merge($simpleSelects, $aggregates))
->leftJoin('videos as b', function ($join) use ($emails) {
$join->on('b.tutor_id', 'a.id')
->whereIn('users.email_address', $emails);
})
->groupBy('users.id')
->get();
Try to remove this line:
->where('users.id', 'videos.tutor_id')
List item
after sql code convert into laravel
DB::select('posts.id','posts.title','posts.body')
->from('posts')
->where('posts.author_id', '=', 1)
->orderBy('posts.published_at', 'DESC')
->limit(10)
->get();

codeigniter limit query not working

I want make a pagination than i find this problem. pagination limit query not working properly.
if($this->input->get('page'))
{
$start = abs(($this->input->get('page', TRUE)-1)*$config['per_page']);
}else{
$start = 0;
}
$condition = array();
if (preg_match('/WMV/', $whatFind)) {
$condition = array('registerId' => $whatFind);
}
$results = $this->db->
group_by('registerId')->
//($start, $config['per_page'])->
order_by('id', 'desc')->
get_where('tbl_applications', $condition)->
result();
You need to use the limit
$this->db->limit(X);
where X is the limit rows to return
$results = $this->db
->group_by('registerId')
->limit($start)
->order_by('id', 'desc')
->get_where('tbl_applications', $condition)
->result();
If you want to limit with a fixed digit (10), then you should do this in your query
->limit(10)
Hello you need to define limit and add in you query.
May below link will help you
Codeigniter Pagination From Database limit, offset

how to convert this simple sql query to doctrine querybuilder

I'm using php doctrine, and i can't convert this sql query to querybuilder .
i have problems with "group by"
any help please ?
SELECT * FROM message WHERE sender_id='2' OR receiver_id = '2' Group By (if(sender_id > receiver_id, sender_id, receiver_id)) , (if(sender_id <= receiver_id, sender_id,receiver_id)) Order BY createdAt DESC
this is what i did but i need condition on groupby
$queryBuilder = $this->createQueryBuilder('m');
$queryBuilder->where('m.sender = :user or m.receiver =:user')
->groupBy('m.sender','m.receiver')
->orderBy('m.createdAt', 'Desc')
->setParameter('user', $user);
This should probably work:
$qb = $this->createQueryBuilder('m');
$qb->where($qb->expr()->orX(
$qb->expr()->eq('m.sender', ':user'),
$qb->expr()->eq('m.receiver', ':user')
))->groupBy('m.sender')
->addGroupBy('m.receiver')
->orderBy('m.createdAt', 'DESC')
->setParameter('user', $user);
So apart from factoring out your where statement into relevant expr() statements (documentation) the only other change is splitting your groupBy into groupBy and then addGroupBy. You can do the same if you ever need to order by more than one things (orderBy and addOrderBy).