Query max Codeigniter - codeigniter

I have a query that result 2 data(s) with the same employee
$this->load->library('datatables');
$this->datatables->select('a.employee_id, a.name, b.employee_position');
->from('employee a')
->join('employee_position b','b.employee_id = .a.employee_id AND `b`.`deleted`=0 AND `c`.`date_start` <= "'.$now_date.'"','inner')
$data = $this->datatables->get_adata();
$aaData = $data->aaData;
I wan't only one data appear which is choosing the max data on date_start column, how to do it?

Add these two lines in your code:
$this->db->order_by('c.date_start', 'DESC');
$this->db->limit(1, 1);

Related

how to combine queries yii2

I have a query with 2 tables. I want to combine these two queries into one query. how do?
public function actionGroup()
{
$query1 = (new \yii\db\Query())
->select(['lao',new \yii\db\Expression('COUNT(lao)'),'nama_ptgs', new \yii\db\Expression('SUM(outstanding)')])
->from('debitur')
->groupBy('lao')
->all();
$query2 = (new \yii\db\Query())
->select(['lao', new \yii\db\Expression('SUM(tgt_pergeseran)')])
->from('resume')
->groupBy('lao')
->all();
return $this->render('outstanding', [
'query1' => $query1,
'query2' => $query2,
]);
}
example sql
SELECT debitur.lao, debitur.Outstanding, debitur.jumlah, resume.Target FROM ( SELECT lao, SUM(outstanding) as Outstanding, COUNT(lao) as jumlah FROM debitur GROUP BY lao )debitur INNER JOIN ( SELECT lao, SUM(tgt_pergeseran) as Target FROM resume GROUP BY lao ) resume ON debitur.lao = resume.lao
error undefined index
print($query);
result
The raw query you provided does not have any where() condition for the main query
SELECT debitur.lao, debitur.Outstanding, debitur.jumlah, resume.Target
FROM
(SELECT lao, SUM(outstanding) as Outstanding, COUNT(lao) as jumlah FROM debitur GROUP BY lao) debitur
INNER JOIN
(SELECT lao, SUM(tgt_pergeseran) as Target FROM resume GROUP BY lao) resume
ON debitur.lao = resume.lao
If that is the complete and correct query that show you the right results in the phpmyadmin widow, you need to use the sub query like below
$subQueryFrom = new \yii\db\Query();
$subQueryFrom->select(['lao', new \yii\db\Expression('SUM(outstanding) as Outstanding, COUNT(lao) as jumlah')])
->from('debitur')
->groupBy('lao');
$subQueryJoin = new \yii\db\Query();
$subQueryJoin->select(['lao', new \yii\db\Expression('SUM(tgt_pergeseran) as Target')])
->from('resume')
->groupBy('lao');
$query = new \yii\db\Query();
$results = $query->select(['debitur.lao', 'debitur.Outstanding', 'debitur.jumlah', 'resume.Target'])
->from(['debitur' => $subQueryFrom])
->innerJoin(['resume' => $subQueryJoin], 'debitur.lao = resume.lao')
->all();
You can now use the $result in your view which holds the records against your query.
return $this->render('outstanding', [
'results' => $results,
]);
In order to combine the results from 2 queries from 2 different tables you can use the Union Operator. From the link there are necessary conditions though:
Each SELECT statement within UNION must have the same number of
columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the same order
In order for this to work for you, you need to alter your queries as follows:
$query1 = (new \yii\db\Query())
->select(['lao',
new \yii\db\Expression('COUNT(lao) as count_column'),
'nama_ptgs',
new \yii\db\Expression('SUM(outstanding) as sum_column'),
new \yii\db\Expression('NULL as tgt_sum')])
->from('debitur')
->groupBy('lao');
$query2 = (new \yii\db\Query())
->select(['lao',
new \yii\db\Expression('NULL as count_column'),
new \yii\db\Expression('NULL as nama_ptgs'),
new \yii\db\Expression('NULL as sum_column'),
new \yii\db\Expression('SUM(tgt_pergeseran) as tgt_sum'),
])->from('resume')
->groupBy('lao');
In short if your first table contains columns a and b, and your second contains columns a and c. Then what you need to do is select(['a','b','NULL as c']) from the first and select(['a','NULL as b','c']) from the second so that you can combine the two results
Then the combined query is simply:
$combinedQuery = $query1->union($query2);

Refactor Laravel Query

I have a query that I have built, and I am trying to understand how I can achieve the same thing but in one single query. I am fairly new to Laravel and learning. Anyway someone could help me understand how I can achieve what I am after?
$activePlayerRoster = array();
$pickupGames = DB::table('pickup_games')
->where('pickupDate', '>=', Carbon::now()->subDays(30)->format('m/d/Y'))
->orderBy('pickupDate', 'ASC')
->get();
foreach ($pickupGames as $games) {
foreach(DB::table('pickup_results')
->where('pickupRecordLocatorID', $games->recordLocatorID)
->get() as $activePlayers) {
$activePlayerRoster[] = $activePlayers->playerID;
$unique = array_unique($activePlayerRoster);
}
}
$activePlayerList = array();
foreach($unique as $playerID) {
$playerinfo = DB::table('players')
->select('player_name')
->where('player_id', $playerID)
->first();
$activePlayerList[] = $playerinfo;
}
return $activePlayerList;
pickup_games
checkSumID
pickupDate
startTime
endTime
gameDuration
winningTeam
recordLocatorID
pickupID
1546329808471
01/01/2019
08:03 am
08:53 am
50 Minute
2
f47ac0fc775cb5793-0a8a0-ad4789d4
216
pickup_results
id
checkSumID
playerID
team
gameResult
pickOrder
pickupRecordLocatorID
1
1535074728532
425336395712954388
1
Loss
0
be3532dbb7fee8bde-2213c-5c5ce710
First, you should try to write SQL query, and then convert it to Laravel's database code.
If performance is not critical for you, then it could be done in one query like this:
SELECT DISTINCT players.player_name FROM pickup_results
LEFT JOIN players ON players.player_id = pickup_results.playerID
WHERE EXISTS (
SELECT 1 FROM pickup_games
WHERE pickupDate >= DATE_FORMAT(SUBDATE(NOW(), INTERVAL 30 DAY), '%m/%d/%Y')
AND pickup_results.pickupRecordLocatorID = recordLocatorID
)
Here I'm assuming you know what you're doing with this dates comparison, because it looks weird to me.
Now, let's convert it to Laravel's code:
DB::table('pickup_results')
->select('players.player_name')->distinct()
->leftJoin('players', 'players.player_id', '=', 'pickup_results.playerID')
->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('pickup_games')
->where('pickupDate', '>=', Carbon::now()->subDays(30)->format('m/d/Y'))
->whereRaw('pickup_results.pickupRecordLocatorID = recordLocatorID');
})
->get();
Basically, I would reduce the query to its SQL variant to get directly at its core.
The essence of the query is
select `x` FROM foo WHERE id IN (
select distinct bar.id from bar join baz on bar.id = baz.id);
This can be interpreted in Eloquent as:
$thirtyDaysAgo = Carbon::now()->subDays(30)->format('m/d/Y');
$playerIds = DB::table('pickup_games')
->select('pickup_games.player_id')
->join(
'pickup_results',
'pickup_results.pickupRecordLocatorID',
'pickup_games.recordLocatorID')
->where('pickupDate', '>=', $thirtyDaysAgo)
->orderBy('pickupDate', 'ASC')
->distinct('pickup_games.player_id');
$activePlayers = DB::table('players')
->select('player_name')
->whereIn('player_id', $playerIds);
//>>>$activePlayers->toSql();
//select "player_name" from "players" where "player_id" in (
// select distinct * from "pickup_games"
// inner join "pickup_results"
// on "pickup_results"."pickupRecordLocatorID" = "pickup_games"."recordLocatorID"
// where "pickupDate" >= ? order by "pickupDate" asc
//)
From the resulting query, it may be better to refactor the join as relationship between the Eloquent model for pickup_games and pickup_results. This will help to further simplify $playerIds.

get all rows in single query with multiple id

I have a asset_request table with fields id and request_id.
I want to select multiple rows with specific ids.
$ids = $request->ids // 5,6
I want to select only rows with ids of 5 and 6 in request table
$ids = $request->ids;
$asset_request = asset_request::whereIn('id',array($ids))->first(); //gets only 6th row.
I need to get all rows matching the given ids.
To clarify after a chat discussion with the Op:
The Op was passing back a string request, therefore, the Op needed to change the following:
$id = $request->id;
$ids = str_split(str_replace(',', '', $id));
$asset_request = asset_request::whereIn('id', $ids)->get();
First you are calling the first method which will return only the first row matched.
You need to call get method to get all rows matched.
Secondly if you are sending ids as a comma separated string you need to convert it to array using explode.
$ids = $request->ids;
$asset_requst = asset_request::whereIn('id', explode(",", $ids))->get();
DB::table('asset_request')
->whereIn('id', (array) $request->ids)
->get();
or
TableModel::whereIn('id', (array) $request->ids)->get();

Active records class in CodeIgniter

Basicly i have two tables photos and users. I wanna join tables and Update colums image_max and image_min. I get error unknown colum username. In which way i can join two tabels and get data from both. My sintax is:
$this->db->select('*');
$this->db->from('photos');
$this->db->join('users', 'photos.id = users.id');
$this->db->where('username',$username);
$this->db->update('photos',$data);
And I get error
Unknown column username in where clause
UPDATE `photos` SET `image_max` = '', `image_min` = '' WHERE `username` = 'wwww'
apparently you need a letter on the table should say "users.username", check that.
Greetings.
$this->db->select('*');
$this->db->from('photos');
$this->db->join('users', 'photos.id = users.id');
$this->db->where('users.username',$username);
$this->db->update('photos',$data);
You don't need to use "select and from" before upload fields, just update in this way
$data = array('image_max'=> 4, 'image_min' => 1);
$this->db->join('users', 'photos.id = users.id');
$this->db->where('username',$username);
$this->db->update('photos',$data);

Codeigniter: Select from multiple tables

How can I select rows from two or more tables?
I'm setting default fields for a form, and I need values from two tables...
My current code reads:
$this->CI->db->select('*');
$this->CI->db->from('user_profiles');
$this->CI->db->where('user_id' , $id);
$user = $this->CI->db->get();
$user = $user->row_array();
$this->CI->validation->set_default_value($user);
The example in the User Guide should explain this:
$this->db->select('*'); // <-- There is never any reason to write this line!
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();
// Produces:
// SELECT * FROM blogs
// JOIN comments ON comments.id = blogs.id
See the whole thing under Active Record page in the User Guide.
Just add the other table to the "->from()" method. Something like:
$this->db->select('t1.field, t2.field2')
->from('table1 AS t1, table2 AS t2')
->where('t1.id = t2.table1_id')
->where('t1.user_id', $user_id);
I think the question was not so much about joins as how to display values from two different tables - the User Guide doesn't seem to explain this.
Here's my take:
$this->db->select('u.*, c.company, r.description');
$this->db->from('users u, company c, roles r');
$this->db->where('c.id = u.id_company');
$this->db->where('r.permissions = u.permissions');
$query = $this->db->get();
I think the syntax is incorrect.
You need to select one record. I have two tables, and I have an id from one table transfer by parameter, and the relation of both tables.
Try this
$this->db->select('*')
->from('student')
->where('student.roll_no',$id)
->join('student_details','student_details.roll_no = student.roll_no')
->join('course_details','course_details.roll_no = student.roll_no');
$query = $this->db->get();
return $query->row_array();
$SqlInfo="select a.name, b.data fromtable1 a, table2 b where a.id=b.a_id";
$query = $this->db->query($SqlInfo);
try this way, you can add a third table named as c and add an 'and' command to the sql command.
// Select From Table 1 All Fields, and From Table 2 one Field or more ....
$this->db->select('table1.*, table2.name');
$this->db->from('table1, table2');
$this->db->where('table2.category_id = table1.id');
$this->db->where('table2.lang_id',$id); // your where with variable
$query = $this->db->get();
return $query->result();

Resources