fetching field in laravel query - php

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();

Related

Laravel orwhere and whereBetween query not working together

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();

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

Codeigniter, join of two tables with a WHERE clause

I've this code:
public function getAllAccess(){
$this->db->select('accesscode');
$this->db->where(array('chain_code' => '123');
$this->db->order_by('dateandtime', 'desc');
$this->db->limit($this->config->item('access_limit'));
return $this->db->get('accesstable')->result();
}
I need to join it with another table (codenamed table), I've to tell it this. Not really a literal query but what I want to achieve:
SELECT * accesscode, dateandtime FROM access table WHERE chain_code = '123' AND codenames.accselect_lista != 0
So basically accesstable has a column code which is a number, let us say 33, this number is also present in the codenames table; in this last table there is a field accselect_lista.
So I have to select only the accselect_lista != 0 and from there get the corrisponding accesstable rows where codenames are the ones selected in the codenames.
Looking for this?
SELECT *
FROM access_table a INNER JOIN codenames c ON
a.chain_code = c.chain_code
WHERE a.chain_code = '123' AND
c.accselect_lista != 0
It will bring up all columns from both tables for the specified criteria. The table and column names need to be exact, obviously.
Good start! But I think you might be getting a few techniques mixed up here.
Firstly, there are two main ways to run multiple where queries. You can use an associative array (like you've started to do there).
$this->db->where(array('accesstable.chain_code' => '123', 'codenames.accselect_lista !=' => 0));
Note that I've appended the table name to each column. Also notice that you can add alternative operators if you include them in the same block as the column name.
Alternatively you can give each their own line. I prefer this method because I think its a bit easier to read. Both will accomplish the same thing.
$this->db->where('accesstable.chain_code', '123');
$this->db->where('codenames.accselect_lista !=', 0);
Active record will format the query with 'and' etc on its own.
The easiest way to add the join is to use from with join.
$this->db->from('accesstable');
$this->db->join('codenames', 'codenames.accselect_lista = accesstable.code');
When using from, you don't need to include the table name in get, so to run the query you can now just use something like:
$query = $this->db->get();
return $query->result();
Check out Codeigniter's Active Record documentation if you haven't already, it goes into a lot more detail with lots of examples.

Weird MYSQL results using PDO::FETCH_ASSOC without column alias

I have a simple left join query.
SELECT e.employee_id as employee
, e.badge_id as badge
, e.first_nm as first
, e.last_nm as last
, e.work_phone as work_ph
, e.mobile_phone as mobile_ph
, e.manager_id as man_id
, e.title_id as titl_id
, e.username as user
, e.start_dt as start
, m.employee_id as memp_id
, m.last_nm as m_last
, m.first_nm as m_first
, t.title_nm as titl_nm
FROM employee e
left join employee m
on e.manager_id = m.employee_id
left join title t
on e.title_id = t.title_id
WHERE e.employee_id = 1
If I use column aliases as I have done above, the query works fine. If I do not use aliases, however, some values do not get returned. For example, the following returns a space if I do not give the column an alias.
e.first_nm as first //returns "Robert"
e.first_nm //returns ""
e.first_nm as first_nm //returns "" (alias matches column name)
In this same query,
e.middle_nm //will return "P"
regardless of whether it has an alias or not. I'm baffled.
I have given my tables aliases and I have used the table alias in the column names so there shouldn't be any ambiguous column names.
Any thoughts would be appreciated.
Thanks,
Rob
You have two columns with same name as first_nm and problably the PDO don´t know what return to your code then return simple "". Although they are in diferent tables when came to a record they have the same name... you see the problem?
You have two columns with same name as first_nm and mysql knows how to return them all right, and then return simple "first_nm" for both. And then PDO have to assign them to array members, making field names as array keys. There is only one way, like this
$row['first_nm'] = first col;
$row['first_nm'] = second col;
If you try to see into $row, how many entries you will find?
So, you either have to use FETCH_ROW or give your fields distinct names. It's neither mysql nor PDO to blame - it's just how the things work.

codeigniter select as

how doHow do we do
select table.value as table_value from table in codeigniter?
The AS part doesnt work because when i try to access the value,
this doesnt work:
$qry_inp = 'select table.value as table_value from table '
$query = $this->db->query($qry_inp);
echo $query->row('table_value ');// this will be empty, but it shouldn`t be
doesn`t matter if its in AR or simple query
Pretty simple thing.
$this->db->select('COLUMN_ACTUAL_NAME as `COLUMN_NAME_YOU_WANT_TO_SHOW`');
i'm joining two tables in which column names are same so i separate both tables columns by using as keyword , this is how you can use AS in codeigniter
$this->db->select("departments.name AS 'dname'");
$this->db->select('positions.name');
Where is that behaviour documented? row doesn't take a column name as a parameter; it optionally takes a row number, and that's it. Access it like any other field:
echo $query->row()->table_value;

Categories