Get random element from MySql using Laravel 5.4 - php

I display an element randomly from my test table, so how can I get the id of this element:
$tests= DB::table('test')->inRandomOrder()->limit(1)->get();
because I want to compare it with an other id

->get() returns a Collection or records from your test table. You need to use a loop to compare a single record's value:
$id = 1; // Or whatever you're comparing to
$tests = DB::table('test')->inRandomOrder()->limit(1)->get();
foreach($tests AS $test){
dd($test->id == $id);
}
Or simply use ->first() to return a single record from test:
$id = 1;
$test = DB::table('test')->inRandomOrder()->first();
dd($test->id == $id);

->get(); method return instance of \Illuminate\Database\Eloquent\Collection. For getting a single instance use ->first();method. See also official docs https://laravel.com/docs/5.5/queries#ordering-grouping-limit-and-offset For example.
$test = DB::table('test')->inRandomOrder()->first();
if ($test->id == $id) {
// your logic
}

Related

WHERE_IN returns only first match in codeigniter

I am trying to get a list of coupons through ajax when the checkboxes are selected. So everything else is working fine but the query is returning only the first match.
So my query is:
$this->db->from('tbl_coupons');
if($storeids !=''){
$ids = array($storeids);
$this->db->where_in('coupon_store', $ids );
}
$this->db->where('coupon_cat', $catid);
$this->db->where('coupon_status', 'active');
$query = $this->db->get();
if ($query->num_rows() > 0) {
$ds = $query->result_array();}
According to this my SQLquery becomes
SELECT * FROM `tbl_coupons`
WHERE `coupon_store` IN('1,97')
AND `coupon_cat` = '16'
AND `coupon_status` = 'active'
But this query is returning values with coupon_store=1 and no results are coming for coupon_store=97
I checked values for coupon store 97 which exists in that category.
use below way if data exist it will be part of query.
storeids = explode(',',storeids);
$ids = array();
foreach($storeids as $val){
$ids[] = $val;
}
if(!empty($ids)){
$this->db->where_in('coupon_store', $ids );
}
hope it will create proper sql query
The query is mostly correct, except at line 2, where you need to make the change as:
WHERE coupon_store IN('1','97')
everything else remains the same.

count and check json query result

I am handling three scenarios :
1) If query returns no result
2) if query returns one result
3) if query returns two or more result
This is my query :
$events = DB::table('bookings')
->join('events','bookings.event_id','=','events.id')
->join('spots','bookings.spot_id','=','spots.id')
->join(DB::raw('(select S.event_id,sum(S.spaces) as sum_spaces from spots S group by S.event_id) d'), function($join)
{
$join->on('bookings.event_id', '=', 'd.event_id');
})
->select('bookings.event_id','events.name', 'spots.event_date','d.sum_spaces',
DB::raw('COUNT(bookings.event_id) as tb'))
->groupBy('bookings.event_id')
->get();
I get $events in json format like this :
[] = 0
[{"event_id":1,"name":"Yoga","event_date":"2016-05-02","sum_spaces":"450","tb":6}] = 1
[{"event_id":1,"name":"Yoga","event_date":"2016-05-02","sum_spaces":"100","tb":16},{"event_id":2,"name":"Yoga","event_date":"2016-05-02","sum_spaces":"450","tb":6},{"event_id":3,"name":"blah","event_date":"2016-05-02","sum_spaces":"250","tb":6}] = 3
If you see that 0,1 and 3. thats what I want to know for a given resultant query.
I need to check if the above result has how many results. How can I find this
Because this is how I am handling the scenarios :
if(empty($events))
{
//sets default value
}
else if(check if $results have one and only one result)
{
//Do something
}
else
{
//here I can handle if $events query have more than one result.
}
If I understood you correctly, you need to count() them:
$numberOfResults = count($events);

Where Operator In Laravel

I need to use where operator to check some ids in my table as the following
$subScIDs = SubjectSchedule::where('subject_start_id',Input::get('substID'))
->whereNull('deleted_at')
->select('id')->get();
$subScIDsArray = array() ;
foreach ($subScIDs as $id)
{
$subScIDsArray [] = $id->id ;
}
// here my issue
$subScInStudAttends = StudentAttendees::whereIn('subject_schedule_id',$subScIDsArray)
->select('subject_schedule_id')->get();
if ($subScInStudAttends)
{
return " true " . $subScInStudAttends;
}else{
return "false";
}
My issue in this code
$subScInStudAttends = StudentAttendees::whereIn('subject_schedule_id',$subScIDsArray)
->select('subject_schedule_id')->get();
whereIn working well it fetch any id in $subScIDsArray, but i need to check each id of ids if one id in $subScIDsArray not equal subject_schedule_id' return false ;
How I Can do it ?
Any Suggestions ?
You can check the length of the array that contains the ids against the length of the records returned.
if( count($subScIDsArray) == count($subScInStudAttends) ){
// all IDs in the array have a corresponding record in the database
}
Or better, if your application logic permits it, simply get the count of the records and then compare with the length of the ids array.
$subScInStudAttendsCount = StudentAttendees::whereIn('subject_schedule_id', $subScIDsArray)->count('subject_schedule_id');
if( count($subScIDsArray) == $subScInStudAttendsCount ){
// all IDs in the array have a corresponding record in the database
}
This code assumes the ids in your database are all unique.

Yii createCommand not not returning correct results

I am trying to get a random ID from a table with a specific visiblity=2 clause but I am having issues getting it to return the ID, it says Undefined index: id.
$space = Yii::app()->db->createCommand()
->select('id')
->from('space')
->where('id=rand() AND visibility=2')
->limit(1)
->queryAll();
//->queryRow();
echo $space['id'];
Is his not the correct way?
I figured out another solution using the already loaded info from my original version without guest check.
$max = Space::model()->count();
$randId = rand(0,$max);
$space = Space::model()->find(array('offset'=>$randId));
if ($space->attributes['visibility'] == 2) {
You can use ORDER BY RAND() instead of id = rand(). Also you can use ->queryScalar() to get only ID directly.
$space = Yii::app()->db->createCommand()
->select('id')
->from('space')
->where('visibility = 2')
->order('RAND()')
->limit(1)
->queryScalar();
echo $space;
Keep in mind that RAND() is slow solution. Check alternatives.
Also, if you get no entries from database, you have to check that case:
if (!empty($space)) { // id will never be 0
// Do something with $space
} else {
throw new CHttpException(404, 'No data found');
}
You are using the random id in where clause, therefore $space maybe an empty array based on condition. For example if you don't have a record with id == 3 and random generated id is 3, then $space is an empty value. So $space['id'] cause Undefined index error. You need to make sure the array is not empty and then echo id of array:
if($space != null)
echo $space['id'];
queryAll method gives you an array with database objects.
For your purpose you can use simpler and more understandable code:
$spaceId = Yii::app()->db->createCommand()
->select('id')
->from('space')
->where('visibility=2')
->orderBy(RAND())
->limit(1)
->queryScalar();
echo $spaceId;

How do i change the column names in a result set and create a new result set in PHP with modified column names

Example: my current result set:
array(7) {[0]=>array(2)
{ ["class_id"]=>string(1) "1"["class"]=>string(3)"1st"}
{ ["class_id"]=>string(1) "2"["class"]=>string(3)"2nd"}
{ ["class_id"]=>string(1) "3"["class"]=>string(3)"3rd"}
I want a new result set as :
array(7) {[0]=>array(2)
{ ["new_id"]=>string(1) "1"["new_class"]=>string(3)"1st"}
{ ["new_id"]=>string(1) "2"["new_class"]=>string(3)"2nd"}
{ ["new_id"]=>string(1) "3"["new_class"]=>string(3)"3rd"}
I dont want this to affect the column names in my database. only the result set.
Show us your query.. If you're doing, for example, the following query:
SELECT class_id, class FROM table;
Change it to this:
SELECT class_id AS new_id, class AS new_class FROM table;
Changing it in the query is hands-down the best way to do it, as you're not having to do any extra work within PHP, however you could also amend them in PHP, of course.
// where $resultset is your original results..
foreach ($resultset as &$result) {
$result_ = array('new_id' => $result['class_id'], 'new_class' => $result['class']);
$result = $result_;
}
Note that neither of these methods would affect your database columns. The only way to do that would be via an ALTER|MODIFY TABLE statement.
try this
function rename_key(&$array, $oldkey, $newkey) {
// remember here we send value by reference using `&`
if(array_key_exists($oldkey,$array))
{
$array[$newkey] = &$array[$oldkey];
unset($array[$oldkey]);
}
return $array;
}
foreach($input as $k)
{
rename_key($k, 'class_id', 'new_id');
rename_key($k, 'class', 'new_class');
$output[]=$k;
}
echo "<pre>";
print_r ($output);
In foreach cycle. Create a new array with needed to you colums from existing result set.

Categories