How can put a MYSQL sentence in laravel: - mysql

SELECT Code_tank, temperature, salinity, PH, parameters.created_at as created_at FROM parameters WHERE id IN (SELECT MAX(id) FROM parameters group by code_Tank) ORDER BY code_tank ASC;
I have been trying to put this SQL sentence in laravel but could not, this is the code with that i was trying:
$testMonitor= DB::table('parameters')
->select('code_Tank', 'salinity', 'PH', 'temperature',
DB::raw('parameters.created_at AS created_at'))
->whereIn('id', DB::raw('SELECT MAX(id) FROM parameters group by code_Tank'))
->orderby('code_Tank', 'asc')->get();
And this is the error, I assumed that one of the parameters in WHEREIN must be an array but I can't think of any other way to accommodate the SQL statement in laravel, please if you could help me
TypeError: Argument 1 passed to Illuminate/Database/Query/Builder::cleanBindings() must be of the type array, object given, called in C:/laragon/www/SoftwareOzimandias/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php on line 907

DB::Raw() will return an object as the second parameter for whereIn, but whereIn want to take the parameter that is array.
You can use closure, check the where-clauses reference:
DB::table('parameters')->whereIn('id', function($query){
$query->select(DB::raw('MAX(id)'))
->from('parameters')
->groupBy('code_Tank');
})->orderby('code_Tank', 'asc')
->select('code_Tank', 'salinity', 'PH', 'temperature',
DB::raw('parameters.created_at AS created_at'))
->get();

Related

groupBy on laravel

$tren = DB::table('suka')
->join('buku', 'buku.ISBN', '=', 'suka.ISBN')
->join('user', 'user.id_user', '=', 'suka.id_user')
->raw('count(*) as total')
->groupBy('suka.ISBN')
->orderBy('maximum')
->LIMIT(2)
->get();
I want to group a join table by ISBN and then find the maximum count of them and take 2 of the most.
here is the error message
Call to undefined method Illuminate\Database\Query\Expression::groupBy()
There is more than one ISBN column in the result set (because it exists in multiple tables). You should specify which table's ISBN column you want to group by in your group by call.
Also, try calling selectRaw instead of raw:
->selectRaw('count(*) as total')
You can read more about raw queries in this documentation.

Laravel QueryBuilder - Different result with `where()` and `whereRaw()` for the identical Query

I'm working on a laravel application Where I have two very similar QueryBuilder but producing different result in both conditions.
Query 1:
$ids = $this->model->leftJoin('feed', 'agents.identifier', '=', 'feed.identifier')
->whereRaw('feed.active <> agents.feed_status')
->pluck('id');
dd(count($ids)); // print 485236
Query 2:
$ids = $this->model->leftJoin('feed', 'agents.identifier', '=', 'feed.identifier')
->where('feed.active', '<>', 'agents.feed_status')
->pluck('id');
dd(count($ids)); // print 4259
I would like to know the key difference between these two QueryBuilder. Why is it producing different results, although it seems identical?
And which query returns the correct result? if I would like to find the records from agents where feed_status is not equel to feed.active.
it seem I have got the clarification. Howevere I would like to share my R&D here. Incase if anyone else got the same problem.
I have printed the raw query and get where() seems consider the third parameter as string compare instead of field compare. That's why seems the result is different.
However when we run the query with whereRaw() it's treated this as table field comparision.
Laravel Code:
$ids = $this->model->leftJoin('feed', 'agents.identifier', '=', 'feed.identifier')
->whereRaw('feed.active <> agents.feed_status')
->pluck('id');
MySql Query:
"select * from `agents` left join `feed` on `agents`.`identifier` = `feed`.`identifier` where feed.active <> agents.feed_status"
# where feed.active <> agents.feed_status
Laravel Code:
$ids = $this->model->leftJoin('feed', 'agents.identifier', '=', 'feed.identifier')
->where('feed.active', '<>', 'agents.feed_status')
->pluck('id');
MySql Query:
"select * from `agents` left join `feed` on `agents`.`identifier` = `feed`.`identifier` where `feed`.`active` <> 'agents.feed_status'"
# where feed.active <> 'agents.feed_status'
Yes, the results were meant to be different.
As where method compares a column with a literal value
->where('table.column', 'cond', 'value')
If you are looking to make comparisons in two columns without using whereRaw method; you should instead use whereColumn method
->whereColumn('table1.column1', 'cond', 'table2.column2')

Dynamically passing of parameter in rails sql query

Below is an SQL query which fetches some data related to user.
def self.get_user_details(user_id)
result = Event.execute_sql("select replace(substring_index(properties, 'text', -1),'}','') as p, count(*) as count
from ahoy_events e where e.user_id = ?
group by p order by count desc limit 5", :user_id)
return result
end
I want to dynamically pass values to user id to get the result.
I am using the below method to sanitize sql array, but still it returns no result. The query works fine if given static parameter.
def self.execute_sql(*sql_array)
connection.execute(send(:sanitize_sql_array, sql_array))
end
Because the query is complicated I am couldn't figure out the ActiveRecord way to get the results.
Is there any way I could get this sorted out?
I don't know why that should not work. May SQL-Syntac SELECT * FROM users ...
dynamic passing some other way you can do this: "some string #{user.id#ruby code} some more string"
You can do querys in Activerecord like this: User.where(id: user.id).where(field2: value2).group_by(:somevalue).order(:id)

Get sum of payments grouped by payment type

SELECT payment_type, sum(total_received) FROM payments GROUP BY payment_type
In MySQL gives me a nice list of all my payment types together with my totals for that type.
-
Payment::all()->groupBy('payment_type')->sum('total_received')
in Eloquent gives me absolutely nothing.
What is the Eloquent equivalent to the above MySQL query?
Best would be using lists, since returning Model with just 2 properties that you want, is redundant:
Payment::selectRaw('payment_type as type, sum(total_received) as sum')
->groupBy('type')
->lists('sum', 'type');
// returns array, something like this:
array(
'type1' => '25',
'type2' => '50',
...
);
Here is a code block that will work in Eloquent:
$var = DB::table('payments')
->select('payment_type', DB::raw('sum(total_received)'))
->groupBy('payment_type')
->get();

How to pass data dynamically to mysql query

I have following query,
SELECT t_subject.subject, SUM( t_skilllist.skill_level ) AS total_skill, t_users.first_name,
t_skilllist.skill_level
FROM `t_skilllist`
JOIN t_subject ON t_subject.id = t_skilllist.subject_id
JOIN t_users ON t_users.id = t_skilllist.user_id
WHERE t_subject.subject = 'html'
GROUP BY t_users.first_name
ORDER BY total_skill DESC
LIMIT 0 , 30
I want to display subject and skill level for each student. But, for one subject I can do that with above query. As an example for html it works. However, I want to pass more than one subject to the query dynamically. I tried to combined subjects with AND operator but it return empty result set.
How to solve this? How to pass more than two subjects to the query? I am using PHP as server side scripting language.
You can use the IN() clause.
WHERE t_subject.subject IN ('html', 'php', 'and', 'a', 'lot', 'more')