I want to sum of amount by currency wise
I do in SQL like this
select sum(total),currencies.currency_symbol from invoices
join(currencies)
where(invoices.currency_id = currencies.id)
group by(currency_id)
I tried in Laravel like this
$sum = Invoice::sum('total')
->select('currency_symbol')
->join('currencies','invoices.currency_id','=','currencies.id')
->groupBy('currency_id');
return response()->json($sum);
But it throws an error
Symfony\Component\Debug\Exception\FatalThrowableError: Call to a member function select() on string
please give me solution
I think you have to use selectRaw, because the combination of sum and select i don't think will work, you can use one of the two. You might try something like this:
$sum = Invoice::selectRaw('currency_symbol, sum(total) as sum')
->join('currencies','invoices.currency_id','=','currencies.id')
->groupBy('currency_id');
return response()->json($sum);
Related
i want to get contact id who was send chat or was i send chat to him
with native query i can get result but when i implement in laravel its going difficult
this my native query
select * from `users` where `users`.`id` in (
select `to` from messages where `from` = 2 group by `to`
union
select `from` from messages where `to` = 2 group by `from`
)
what i find difficult is how union after group by or group by after union with make same column number, i using merge but the result is wrong
this what i have try in laravel
$to = Message::select('to')->where('from',auth()->id())->groupBy('to')->get();
$from = Message::select('from')->where('to',auth()->id())->groupBy('from')->get();
$tofrom = $to->merge($from);
dd($tofrom);
please if any body can help
Unions are described in the documentation. To achieve your specific requirements you can do:
$final = User::whereIn('id', function ($query) {
$from = Message::select('from')->where('from',auth()->id())->groupBy('from');
$query->from('messages')->where('to',auth()->id())->groupBy('to')->union($from);
})->get();
Disclaimer: I have not actually tested this but I think it should work.
merge() is the method of collection. Not the Eloquent Builder or Query Builder.
However, It think you want to find user.id in the array.
You can convert the collection to array:
$to = Message::where('from',auth()->id())->groupBy('to')->pluck('to');
$from = Message::where('to',auth()->id())->groupBy('from')->pluck('from');
$tofrom = $to->merge($from)->toarray();
User::whereIn('id', $tofrom)->get();
oh finally i got the answer this is code
$contacts = User::select('users.id','users.name','users.email','users.profile_image')
->join('messages',function($join){
$join->on('users.id','messages.from');
$join->orOn('users.id','messages.to');
})
->where(function($query){
$query->where('messages.from',auth()->id())->orWhere('messages.to',auth()->id());
})
->groupBy('users.id','users.name','users.email','users.profile_image')
->get();
I want to convert this code in laravel.
SELECT MAX(date_start) AS DateStart,MIN(date_end) AS DateEnd FROM DBTest
And I try this code
$data = DB::table('DBTest')
->select(max('date_start'), min('date_end')))
->get();
Return Error: max(): When only one parameter is given, it must be an array
I am using laravel 5.2, and SQLyog as database
I am confuse in syntax please help me
You can't use functions in select statement, but you can use raw SQL :
$data = DB::table('DBTest')
->select(\DB::raw('MIN(date_start) AS DateStart, MAX(date_end) AS DateEnd'));
->get();
You can do it like this:
For the max start date:
max = DB::table('DBTest')->select('date_start')->orderBy('date_start', 'desc')->first();
For min end date:
min = DB::table('DBTest')->select('date_end')->orderBy('date_end', 'asc')->first();
You have to use something called selectRaw method in Laravel in order to achieve this result. Chaining method like ->max('columnA')->min('columnB') will not work. So, here is the solution:
$data = DB::table('DBTest')
->selectRaw('MAX(date_start) AS DateStart, MIN(date_end) AS DateEnd')->get();
Try MIN() and MAX() functions in the sql query.
$data = DB::table('DBTest')
->select(\DB::raw('MIN(date_start) AS startDate, MAX(date_end) AS endDate'));
->get();
I´m triying to do an arithmetic operation but i always get error.
This is the query:
public function getAllModifiers($condition)
{
$this->db->select('DM.id AS modifier_id, DM.name, minimum, maximum');
$this->db->select('DMI.id AS item_id, DMI.name AS item_name, `DMI.price * 1.1` AS item_price');
$this->db->from('dishes_modifiers DM');
$this->db->join('dishes_modifiers_items DMI', 'DMI.modifier_id = DM.id', 'left');
$this->db->where($condition);
return $this->db->get()->result();
}
How can i get the item_price * 1.1?
Thanks.
The backticks are used to escape object names (e.g., columns names). Any mathematical operation should be outside this escaping:
$this->db->select(`DMI.price` * 1.1 AS item_price');
# Here -----------^---------^
Check this:
$this->db->where($condition);
This one not checking the data with the database values.
You can use this in where condition
(DMI.price *1.1) > DMI.price *1.1
I have this query:
select substr(id,1,4) as id
from meteo.a2012
group by substr(id,1,4)
I just want to take first 4 numbers to my id row, but I'm trying to do in eloquent, how I do?
Thanks.
You need to use raw expressions so you can use special functions like that.
Model::select(DB::raw('substr(id, 1, 4) as id'))->groupBy(DB::raw('substr(id, 1, 4)'))->get();
Where Model is your Eloquent model you want to run the query on.
G'day
I was able to do it like this in Laravel
$data = DataModel::selectRaw("SUBSTRING_INDEX(EMAIL_COLUMN, '#', 1) as 'alias'")->get();
As a result, I get the alias name (address) from the mail address#domain.net
$ids = Model::get(['id']);
foreach ($ids as $str)
{
$str->id =substr($str->id,1,4);
}
return $ids;
I'm trying to do this:
SELECT
userId, count(userId) as counter
FROM
quicklink
GROUP BY
userId
HAVING
count(*) >= 3'
In doctrine with the querybuilder, I've got this:
$query = $this->createQueryBuilder('q')
->select('userId, count(userId) as counter')
->groupby('userId')
->having('counter >= 3')
->getQuery();
return $query->getResult();
Which gives me this error:
[Semantical Error] line 0, col 103 near 'HAVING count(*)': Error: Cannot group by undefined identification variable.
Really struggling with doctrine. :(
Your SQL is valid, Your query builder statement is invalid
All cause db will execute that query in following order:
1. FROM $query = $this->createQueryBuilder('q')
2. GROUP BY ->groupby('userId') // GROUP BY
3. HAVING ->having('counter >= 3')
4. SELECT ->select('userId, count(userId) as counter')
So as You can see counter is defined after its use in having.
Its SQL Quirk. You can not use definitions from select in where or having statements.
So correct code:
$query = $this->createQueryBuilder('q')
->select('userId, count(userId) as counter')
->groupby('userId')
->having('count(userId) >= 3')
->getQuery();
return $query->getResult();
Do note repetition in having from select
I am going to answer for people who still have this type of error.
First things first, you seem to have translated a native sql query inside a query builder object. More so, you have named your object as q
$query = $this->createQueryBuilder('q');
What this means, in general, is that every condition or grouping etc you have in your logic should address fields of q: q.userId, q.gender, ...
So, if you had written your code like below, you would have avoided your error:
$query = $this->createQueryBuilder('q')
->select('q.userId, count(q.userId) as counter')
->groupby('q.userId')
->having('counter >= 3')
->getQuery();
return $query->getResult();
I think you are missing the 'from' statement
$query = "t, count(t.userId) as counter FROM YourBundle:Table t group by t.userId having counter >1 ";
return $this->getEntityManager()->createQuery($query)->getResult();
This should work. You can even do left joins or apply where clausules.
you can define HAVING parameter via setParameter() method as well
$qb->groupBy('userId');
$qb->having('COUNT(*) = :some_count');
$qb->setParameter('some_count', 3);