Pass multiple IDs, get first record only in Laravel - php

How can I get only the first record using multiple IDs in Laravel? In the following code, $ids has three elements. I want to fetch the first record from table using these three IDs.
$ids = [16, 18, 20];
$listing = Listing::whereIn('id', $ids)->first();

If you want to get the first object with smallest id, you can do:
$listing = Listing::whereIn('id', $ids)->oldest('id')->first();
But better to do this:
$listing = Listing::find(min($ids));
If you want to get an object with the first ID in the array, do this:
$listing = Listing::find($ids[0]);

You can use either limit or oldest function of laravel see below query
$listing = Listing::whereIn('id', $ids)->limit(1)->get(); //using limit
OR
$listing = Listing::whereIn('id', $ids)->oldest('id')->first(); //using oldest()

A possible way to do this would be to sort the id column like so:
$listing = Listing::whereIn('id', $ids)->orderBy('id')->first();

I think you should try this:
$ids=[16,18,20];
foreach($ids as $id){
$listing[] = Listing::where('id', $id)->first();
}
Hope this work for you!

Related

What is the correct method in where_in?

i want to get data using where in condition
my code is below
SELECT `cuc_UserCardsDetail`.*, `cuc_CreditCardType`.`varValidName`
FROM (`cuc_UserCardsDetail`)
JOIN `cuc_CreditCardType` ON `cuc_CreditCardType`.`intGlCode` =
`cuc_UserCardsDetail`.`fk_CardTypeGlCode`
WHERE `cuc_UserCardsDetail`.`intGlCode` IN ('10,29')
AND `chrAccountType` = 'M'
ORDER BY `dtCreateDate` desc
now I have resulted with one row actually in my table there is two-row with related id
i think problem is In('10,29') but i want like ('10','29') or (10,29) how can i do in codeigitor?
i want (10,29) or ('10','29') in where in ..
In CI query builder use
$id= array('10', '20'); # or direct assing your input params
$this->db->where_in('column_name', $id);
Read Looking for Specific Data - Codeigniter.com
Method chaining will accept array in where_in
$intGlCode = array(10, 29);
$this->db->select('`cuc_UserCardsDetail`.*, `cuc_CreditCardType`.`varValidName`');
$this->db->from('cuc_UserCardsDetail');
$this->db->join('cuc_CreditCardType','cuc_CreditCardType.intGlCode =
cuc_UserCardsDetail.fk_CardTypeGlCode');
$this->db->where('chrAccountType','M');
$this->db->where_in('cuc_UserCardsDetail.intGlCode',$intGlCode);
$this->db->order_by('dtCreateDate','DESC');
$data = $this->db->get()->result_array();
Your query look something like
you have to define column chrAccountType from which table, here i assume it from cuc_UserCardsDetail
$this->db->select('ud.*, cc.varValidName');
$this->db->where_in('ud.intGlCode', ['10','29']);
$this->db->where('ud.chrAccountType', 'M');
$this->db->order_by('dtCreateDate', 'desc');
$this->db->join('cuc_CreditCardType cc', 'cc.intGlCode = ud.fk_CardTypeGlCode');
$data = $this->db->get('cuc_UserCardsDetail ud')->result_array();
print_r($data);
where_in() function just in the case of array of data.
$ids = array();
$this->db->where_in('id', $ids);

How to add limit to array data fetched from database in laravel

I'm retrieving the rows from user table and I'm using below code.
<?php $user = User::get(); ?>
I want to add array limit for $user data. I don't want to use paginate();. To add limit I'm using below code but it's not working
$users = array_slice($users, 0,2);
But it's showing below error message
exception 'ErrorException' with message 'array_slice() expects
parameter 1 to be array, object given' in........
How to I add limit to $user?
<?php
$user = User::get();
$user = $user ->limit(10);
?>
try limit or
<?php
$user = User::get();
$user = $user ->take(10);
?>
In recent Laravel versions you can also use:
User::limit(10)->offset(0)->get();
Note that User model must extend Eloquent.
Do you mean to use:
$users = array_slice($user, 0,2);
You are getting the error because $users is a collection, not an array.
You could use the take method
$users = User::get()->take(3);
or the slice method
$users = User::get()->slice(3);
Here are some ways you can achieve this.
Applying the offset and limit directly to the query builder allows you to fetch only the needed rows.
$users = User::skip(5)->take(10)->get();
$users = User::offset(5)->limit(10)->get();
If you insist on working with complete result, then this approach is what to you need. You need to use collection slice method not array_slice since the result is a collection.
$users = User::all();
// Collection slice(offset, limit)
$users = $users->slice(5, 10);

Extract all possible values of AR column in yii2

Several models in yii2 are bound to a database using ActiveRecords. I now want to have a list of all ids of this model. Say, all user IDs when the Model is called User.
Sure I could just fetch all models and iterate over them, much like
$ids = [];
$users = User::find()->all();
foreach ($users as $user) {
$ids[] = $user->id;
}
But I feel there should be an easier way... Thanks in advance.
If you want to stay in ActiveRecord then this accomplishes the same thing:
$ids = User::find()->select('id')->column();
This returns array:
$ids = (new \yii\db\Query)->select('id')->from(User::tableName())->all();

Laravel modifying multiple rows at once

I have an array of $ids.
I'd like to essentially say:
foreach($ids as $id):
$user = User::find(1);
$user->life_expectancy -= 1;
$user->save();
endforeach;
Except I have thousands of ids in the array, and I'd much rather do something like:
$users = User::whereIn('id', $ids)->update(array('life_expectancy' => --1));
To just get it done in a single query. But that isn't going to work... is there another method?
I know I can update multiple users to all have the same life_expectancy, but I'd like it to be a modification of the previous value.
Check out this site, http://community.sitepoint.com/t/one-sql-statement-to-subtract-and-update-a-field-value/4673 if you decide to use a raw query, but looking on laravel's docs I think you can just do this,
$users = DB::table('users')
->whereIn('id', $ids)->decrement('life_expectancy');
App\User::whereIn('id',[1,2])->decrement('life_expectancy');
If you need -2 use next string:
App\User::whereIn('id',[1,2])->decrement('life_expectancy',2);

How to count total number of rows of table in Cakephp

How to count the total number of rows of table and pass it to the variable? For example, I have product table and there are 10 products in it. I want to count all the rows and get the result 10 and pass it to the variable $rowcount. How can I do it?
use find('count')
For example:
$total = $this->Article->find('count');
If you want to use a condition in your query, then pass the conditions array, here is a sample code:
$pending = $this->Article->find('count', array('conditions' => array('Article.status' => 'pending')));
you also try this with condition
$rowcount = $this->Product->find('count', array('conditions' => array('Product.fieldName' => 'value')
u can do it with find('count') method
$this->set('rowcount',$this->Product->find('count'));
or simply use count() function if had already the products in a variable $products to avoid another Mysql query
$this->set('rowcount',count($products));
By Using this you can count data with passing conditions in where
$assignment = TableRegistry::get('Assignment');
$query = $assignment->find();
$query->select(['count' => $query->func()->count('id')]);
$query->where(['Assignment.user_id'=>$user_id]);
$assignment = $query->toArray();
$assignment_count = $assignment[0]->count;
return $assignment_count;
In CakePHP 3.x you can query like this:
$count = $this->Students->find()->count();
Or
TableRegistry::get('Students')->find()->count();
Here student is example model. Replace with your model name.
Thanks.

Categories