Laravel orwhere and whereBetween query not working together - php

I have a situation to filter user from database in a way that to filter from two columns of the table with a particular id and that should be filtered with a range of date.
My code is as shown below.
$fetchSelectedUser=Wallet_Transaction::select('wallet__transactions.from as FromUser','wallet__transactions.type','wallet__transactions.date','wallet__transactions.amount','wallet__transactions.balance_after',
'wallet__transactions.type','wallet__transactions.description','wallet__transactions.to as ToUser','users.name as FromName',DB::raw('(select name from users where users.id = ToUser) as toName'))
->join('users','users.id','=','wallet__transactions.from')
->where('wallet__transactions.from','=',$user_id)->orWhere('wallet__transactions.to','=',$user_id)
->whereBetween('wallet__transactions.db_date',[$fromDate,$toDate])->get();
what I have tried is put a static date, and is not working. Also I removed orWhere and whereBetween independently. That is working. But it will not working together.

Use where() closure to group your conditional query:
$fetchSelectedUser=Wallet_Transaction::select('wallet__transactions.from as FromUser','wallet__transactions.type','wallet__transactions.date','wallet__transactions.amount','wallet__transactions.balance_after',
'wallet__transactions.type','wallet__transactions.description','wallet__transactions.to as ToUser','users.name as FromName',DB::raw('(select name from users where users.id = ToUser) as toName'))
->join('users','users.id','=','wallet__transactions.from')
->where(function($q) use ($user_id){
$q->where('wallet__transactions.from','=',$user_id)->orWhere('wallet__transactions.to','=',$user_id);
})->whereBetween('wallet__transactions.db_date',[$fromDate,$toDate])->get();

Related

fetching field in laravel query

I have two tables user_master and user_teams with common field user_name.
I want to join the table and get the team value group by teams
tried as
$filter_teams = DB::table('user_teams')
->join('user_master','user_master.user_name','=','user_teams.user_name')
->whereIn('user_master.geo',$geo)
->groupBy('user_teams.team')
->pluck('user_teams.team')
->toArray();
by may values are duplicating.I'm using postgresql
since you didn't determine select fields ... the default will be '*'
this is why you are getting duplicated fields ...
just add :
->select('user_teams.team')
and i think that all.
i recommend not using group without aggregation ....
so my advice your query to like this:
$filter_teams = DB::table('user_teams')
->join('user_master','user_master.user_name','=','user_teams.user_name')
->whereIn('user_master.geo',$geo)
->select('user_teams.team')->distinct()
->pluck('user_teams.team')
->toArray();

What is wrong with this laravel query with left join?

I am working on a laravel project(Laravel 6.8). I have a locations table and a dashboards table. I am trying to build a query that will return all matching records from the dashboards table. Looking at another SO question(Laravel 5.4 Raw Join Query), I saw a similar need and tried to adjust the code to fit my needs, but it still doesn't work.
This is what I have right now.
$locations = DB::table('locations')
->selectRaw("site_name,
COUNT(DISTINCT client) as client_count,
GROUP_CONCAT(client_lob) as lobs,
COUNT(DISTINCT client_lob) as lob_count,
SUM(agent_workstations) as aw_sum,
SUM(production_support_workstations) as psw_sum,
locations.*" )
->leftJoin('dashboards', 'locations.id', '=', 'dashboards.location_id')
->whereNotNull('latitude')
->groupBy(['site_name'])
->orderBy('site_name', 'asc')
->get();
It returns only the data from locations without returning anything from dashboards. I can't see what is wrong with this query. Can anyone offer some advice?
Because you never select the dashboard's fields, try to select the dashboard's field like this:
$locations = DB::table('locations')
->selectRaw("site_name,
COUNT(DISTINCT client) as client_count,
GROUP_CONCAT(client_lob) as lobs,
COUNT(DISTINCT client_lob) as lob_count,
SUM(agent_workstations) as aw_sum,
SUM(production_support_workstations) as psw_sum,
locations.*, dashboards.column1, dashboards.column2" )

Laravel 5.6 groupBy on collection doesn't work

GroupBy just doesn't work on collection in Laravel 5.6, it is very annoying when simple things which supposed to work not wirking...
$users = Game::orderBy('game_count', 'desc')->get();
$users_grouped = $users->groupBy('user_id');
As you might guess $users_grouped contains the same collection as $users with the same repeating user_id values.
I don't get why it doesn't work as expected and how to fix it?
At least GROUP BY works with raw DB select hopefully.. But I want to use Eloquent..
You're confusing eloquent's query builder with collections. They are not the same thing.
groupBy on a query builder instance will use an SQL GROUP BY and give one aggregated result for the column(s) you are grouping on.
groupBy on a collection instance will return a new collection that groups all collected items by the given key's value.
https://laravel.com/docs/5.6/collections#method-groupby
If you want to use the query builder's groupBy method, chain it before the get():
$users = Game::orderBy('game_count', 'desc')->groupBy('user_id')->get();
get() executes the query and returns the collection of records.
If you want to group the query by user_id just do the groupBy before the get(), as the following row:
$users = Game::orderBy('game_count', 'desc')->groupBy('user_id')->get();
The rows will be the same. You should make two querys:
$users = Game::orderBy('game_count', 'desc')->get();
$users_grouped = Game::orderBy('game_count', 'desc')->groupBy('user_id')->get();
Temporary solution for this is the raw SQL query:
$users_grouped = DB::select('SELECT COUNT(id) AS theCount, `user_id` from `quiz_games` GROUP BY `user_id` ORDER BY theCount DESC');

Distinct and orderby doctrine querybuilder

I have the following query that I need to get working:
$repository = $this->getDoctrine()->getRepository('AppBundle:ProjectPhaseUser');
$query = $repository->createQueryBuilder('p')
->select('(p2.project) AS projectId')
->leftJoin('AppBundle:ProjectPhase', 'p2', 'WITH', 'p.projectPhase = p2.id')
->where('p.user = ' . $user->getId())
->orderBy('p.assignDate', 'DESC')
->setMaxResults(3)
->getQuery();
Basically there are 2 tables: ProjectPhaseUser and ProjectPhase
What resides in the ProjectPhaseUser table are the users with projectphases and an assigndate. In the ProjectPhase table you have the projectphases and projects they belong to.
What I want is to get the 3 last assigned projects of a particular user.
What the query does now is get the last 3 projectphases their projects. However this gives me duplicate projects since a project can have multiple projectphases. When I try a distinct on the project I get the problem that orderby is not in the select clause. I also have tried groupby which gives me the only full group by mysql error.
How can I achieve this without altering the mysql only full group by option?

Laravel groupBy Database query Builder not working

I have this problem in a query using laravel groupBy, it simply return a groupBy error. I have read the documentation about this but can't really figure it out. I also read the same problem pointing that it is because of postgreSQL that I need to include all the columns in grouBy clause. I tried it but still it doesn't return the distinct values. Please help me with this. Below is my code. Thanks a lot.
Controller function
public function index(){
$purchases = Purchase::groupBy('purchase_order_id')->get();
return view('purchases/purchases_crud', ['allPurchases' => $purchases]);
}
Table to query
Error
QueryException in Connection.php line 680:
SQLSTATE[42803]: Grouping error: 7 ERROR: column "purchases.id" must appear
in the GROUP BY clause or be used in an aggregate function
LINE 1: select * from "purchases" group by "purchase_order_id"
^ (SQL: select * from "purchases" group by "purchase_order_id")
There you have it add group by "purchases.id" or restrict the select to only the operates that are needed.
->select("purchase_order_id","purchases.id")
->groupBy("purchases.id") // add if possible
Agreggates for your case should mean something like ->select("sum(po_total)")
If we group by id, we get all results as id is unique, my mistake. You want something like this
DB::table("purchases")->select("purchase_order_id", DB:raw("sum(po_total)"))->groupBy("purchase_order_id")->g‌​et();
Rule of thumb is you either select a field with Sum() or have it on the group by

Categories