running a mysql query containing division in laravel 5 - php

I want to run this mysql query in Laravel 5 using the DB query :
// SELECT *, rating/number as total FROM `courses` order by total DESC;
This is what I tried :
$query = \DB::table('courses')->select('*');
$courses = $query->addSelect('rating/number as total')
->orderBY('total DESC')
->get();
but, rating/number is considered as a table column . The same thing happens when I tried it inside parenthesis (rating/number).
Any help?

$courses = \DB::table('courses')
->selectRaw('*, rating/number as total')
->orderBY('total', 'DESC')
->get();

Can you use Raw Expressions for it? Maybe something like this:
$courses = \DB::table('courses')
->select(DB::raw('*, (rating / number) as total'))
->orderBy('total DESC')
->get();

Related

Subquery of two related tables in laravel

I want to write the following query in Laravel 5.
SELECT *
FROM loans
WHERE loanAmount > (SELECT IFNULL(SUM(paidLoanAmount), 0)
FROM paid_loans WHERE loanId = loans.id);
I have tried the following, but subquery of PaidLoan seems not work due to loans.id or something else I don't notice.
Loan::where(
'loanAmount',
'<=',
PaidLoan::where('paid_loans.loanId', 'loans.id')
->get()
->sum('paidLoanAmount')
)->get();
You can use a leftJoin on the loan and just add a normal condition.
$payedLoans = Loan::leftJoin('paid_loans', 'paid_loans.loanId', '=', 'loans.id')
->where('loanAmount', '<=', \DB::raw("IFNULL(sum('paid_loans.paidLoanAmount'), 0)"))
->groupBy('loans.id')
->get();

Helpe me to convert SQL query to Laravel eloquent

I have this SQL query:
SELECT *, count(*) as mostView FROM users RIGHT JOIN visitors ON users.id = visitors.user_id GROUP BY users.id HAVING users.isActive=1 AND users.fullName IS NOT NULL AND users.photo_id IS NOT NULL AND users.role_id IN(1, 3) ORDER BY mostView DESC LIMIT 5
It works, but I need convert to Laravel eloquent, i'm using laravel 5.6, could any one helpe me thanks in advance
I'm assuming that you have map the relationship in your Model if you do you can do like below,
$userViews = User::->with('vistors')
->where('isActive',1)
->whereNotNull('fullName')
->whereNotNull('photo_id')
->whereIn('role_id ',[1,3])
->get();
$mostView = $userViews->sortBy(function ($collection) {
return $collection->vistors->count()
})->take(5)
hope this helps
Not going to spoon feeding but can provide you some ideas to convert raw sql to eloquent, your sql should ideally be like this:
User::selectRaw('*', 'count(*) as mostView')
->rightJoin()
->groupBy()
->having()
->where // whereNotNull // wherIn
->orderBy()
->take(5)
->get();
Kindly refer to laravel docs: https://laravel.com/docs/5.6/queries
Thanks for all i'm studies Database: Query Builder on the link
https://laravel.com/docs/5.6/queries
and so i solved my question by myself
the answer is:
$mostViews = DB::table('users')
->rightJoin('visitors', 'users.id' , '=' , 'visitors.user_id')
->select('users.*', DB::raw('count(*) as mostView'))
->where('isActive', '=', '1')
->whereNotNull('fullName')
->where('photo_id', '<>', 'NULL')
->where(function ($q){
$q->where('role_id', '=', '1')
->orWhere('role_id', '=', '3');
})
->groupBy('user_id')
->orderBy('mostView', 'desc')->take(5)->get();

Laravel Query Builder - Ordering on a Custom Column

I want to sort my Laravel query builder results on a custom column (concat of first_name and last_name).
What I have done is-
$summary = DB::table('service_rating')
->join('partners', 'partners.id', '=', 'service_rating.partner_id')
->join('users', 'users.id', '=', 'partners.user_id')
->select(
DB::raw("CONCAT( users.first_name,' ', users.last_name) as lawn_pro"),
DB::raw ('AVG(service_rating.rating) as rating'),
DB::raw ('COUNT(service_rating.rating) as jobs'),
DB::raw ('SUM(service_rating.rating) as payout')
)
->where('customer_id', '=', Auth::user()->id)
->whereRaw('service_rating.created_at >= DATE(NOW()) - INTERVAL '.$no_of_day_to_show.' DAY')
->groupBy('service_rating.partner_id')
->orderBy('lawn_pro', 'asc');
So, I am getting error for this line -
->orderBy('lawn_pro', 'asc');
And error is like this-
Can anyone please help ?
Apparently you are using the count() function on your query, this ignores the select attributes because we only want to know the count of the rows. Because of this, lawn_pro is not available in the query.
I would suggest to execute the query and then count the available rows.
$rows = $summary->get();
$count = count($rows);

Laravel Query Builder - sum() method issue

I'm new to laravel and I have some issues with the query builder.
The query I would like to build is this one:
SELECT SUM(transactions.amount)
FROM transactions
JOIN categories
ON transactions.category_id == categories.id
WHERE categories.kind == "1"
I tried building this but it isn't working and I can't figure out where I am wrong.
$purchases = DB::table('transactions')->sum('transactions.amount')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->select('transactions.amount')
->get();
I would like to get all the transactions that have the attribute "kind" equal to 1 and save it in a variable.
Here's the db structure:
transactions(id, name, amount, category_id)
categories(id, name, kind)
You don't need to use select() or get() when using the aggregate method as sum:
$purchases = DB::table('transactions')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->sum('transactions.amount');
Read more: http://laravel.com/docs/5.0/queries#aggregates
If one needs to select SUM of a column along with a normal selection of other columns, you can sum select that column using DB::raw method:
DB::table('table_name')
->select('column_str_1', 'column_str_2', DB::raw('SUM(column_int_1) AS sum_of_1'))
->get();
You can get some of any column in Laravel query builder/Eloquent as below.
$data=Model::where('user_id','=',$id)->sum('movement');
return $data;
You may add any condition to your record.
Thanks
MyModel::where('user_id', $_some_id)->sum('amount')

Count rows in Laravel 4 database

Hi I am trying to get the current count of my statement below , but I am getting only the count not the whole result:
$admins = DB::table('users')
->select(DB::raw('count(users.id) as admin_count'))
->where('users_roles.role_id', '=' ,0)
->join('users_roles', 'users.id', '=', 'users_roles.user_id')
->orderBy('first_name', 'asc')
->get();
Could you tell me what I am doing wrong?
Thanks
Just use * in your SELECT clause, and you get entire resultset. Then, $admins is an array, and you can get its count using count method.
$admins = DB::table('users')
->select('users.*')
->join('users_roles', 'users.id', '=', 'users_roles.user_id')
->where('users_roles.role_id', '=' ,0)
->get();
I assume you have users_roles.role_id = 0 for exactly once for a user. There are no multiple entries for role_id = 0 for one user right?
I hope this helps.
Or you can use...
$admins = User::roles()->where('role_id', '=', 0)->count();
If the relations are setup correctly that should work.
Resource: http://laravel.com/docs/eloquent#many-to-many
I am not sure how laravel handles nested selects with the query builder, in plain sql, it would look like this
SELECT users.id, (SELECT COUNT(users.id) FROM users) AS admin_count
FROM users
JOIN users_roles
ON user_roles.id = users.id
WHERE users_roles.role_id = 0
ORDER BY first_name
which I am pretty sure you can just assign to a variable and run it like $admins = DB::query($sql)

Categories