codeigniter, result() vs. result_array() - php

I use both result() and result_array().
Usually i like to get my result as array thats why i use result_array() mostly..
But i want to know which is the better approach that i should follow,
Which one of them is more efficient to use in regards to performance?
Here is the Example i am talking about in codeigniter queries
$query = $this->db->get();
$result = $query->result_array();
or is this should be the better approach??
$query = $this->db->get();
$result = $query->result();
also right now i am using result_array in my generic model.

Result has an optional $type parameter which decides what type of result is returned. By default ($type = "object"), it returns an object (result_object()). It can be set to "array", then it will return an array of result, that being equivalent of caling result_array(). The third version accepts a custom class to use as a result object.
The code from CodeIgniter:
/**
* Query result. Acts as a wrapper function for the following functions.
*
* #param string $type 'object', 'array' or a custom class name
* #return array
*/
public function result($type = 'object')
{
if ($type === 'array')
{
return $this->result_array();
}
elseif ($type === 'object')
{
return $this->result_object();
}
else
{
return $this->custom_result_object($type);
}
}
Arrays are technically faster, but they are not objects. It depends where do you want to use the result. Most of the time, arrays are sufficient.

for the sake of reference:
// $query->result_object() === $query->result()
// returns:
Array ( [0] => stdClass Object ( [col_A] => val_1A , [col_B] => val_1B , ... )
[0] => stdClass Object ( [col_A] => val_2A , [col_B] => val_2B , ... )
...
)
// $query->result_array() !== $query->result()
// returns:
Array ( [0] => Array ( [col_A] => val_1A , [col_B] => val_1B , ... )
[1] => Array ( [col_A] => val_2A , [col_B] => val_2B , ... )
...
)
codeigniter docs for result(), and result_array()

result_array() is faster,
result() is easier

result() returns Object type data.
.
.
.
result_array() returns Associative Array type data.

Returning pure array is slightly faster than returning an array of objects.

result() is recursive in that it returns an std class object where as result_array() just returns a pure array, so result_array() would be choice regarding performance. There is very little difference in speed though.

result_array() returns Associative Array type data. Returning pure array is slightly faster than returning an array of objects. result() is recursive in that it returns an std class object where as result_array() just returns a pure array, so result_array() would be choice regarding performance.

in my experince the problem using result() and result_array() in my JSON if using result() there no problem its works but if using result_array() i got error "Trying to get property of non-object" so im not search into deep the problem so i just using result() if using JSON and using result_array() if not using JSON

Related

Pass eloquent collection to array

$task = Task::all();
$sort = $task->sortByDesc('id')->toArray();
return view('welcome')->with('sort',$sort);
I want to pass Eloquent collection object to an array and then sort to iterate through but I get this error:
htmlspecialchars() expects parameter 1 to be string, array given
I don't know what the error means?
Try this
// controller
$task = Task::orderBy('id','DESC')->get();
return view('welcome')->with('task',$task);
// view
#foreach($task as $t)
{{$t->colunm_name}}
#endforeach
Laravel get() returns an array of object

Laravel use of concat with pluck method

I am using Laravel.5.3 and below is my query
$ProjectManagers = Employees::where("designation" , 1)
->pluck(DB::raw('CONCAT(first_name," ",last_name) AS name'),'id');
which throws an error that
Illegal offset type in isset or empty
May i know if this is the correct method ?
if i dont use contact and use like
$ProjectManagers = Employees::where("designation" , 1)->pluck('first_name','id');
which is working correct and giving me result
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[8] => Punit
)
)
Expected Result :
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[8] => Punit Gajjar
)
)
where first name and last name are concatenated.
The most elegant solution is to create an accessor.
Open your Employees class (model) and add an accessor function:
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
After that, just simply use:
$ProjectManagers = Employees::where('designation', 1)->get()->pluck('full_name', 'id');
Try changing the eloquent query to:
$ProjectManagers = Employees::select(
DB::raw("CONCAT(first_name,' ',last_name) AS name"),'id')
->where('designation', 1)
->pluck('name', 'id');
if your column is nullable then you should try this
convert the NULL values with empty string by COALESCE
$ProjectManagers = Employees::select(
DB::raw("CONCAT(COALESCE(`first_name`,''),' ',COALESCE(`last_name`,'')) AS name"),'id')
->where('designation', 1)
->pluck('name', 'id')
->toArray();
I also faced a problem like that with join query here is the solution of my problem
$studentDegree = Student::leftJoin('degree','degree.student_id','=','student.id')
->select(
DB::raw("CONCAT(student.name,'-',degree.name) AS name_degree"),
'student.id'
)->lists('name_degree','id');

Eloquent ORM laravel 5 Get Array of ids

I'm using Eloquent ORM laravel 5.1, and I want to return an array of ids greater than 0, my model is called test.
I have tried :
$test=test::select('id')->where('id' ,'>' ,0)->get()->toarray();
It returns :
Array ( [0] => Array ( [id] => 1 ) [1] => Array ( [id] => 2 ) )
But I want the result to be in simple array like this:
Array ( 1,2 )
test::where('id' ,'>' ,0)->pluck('id')->toArray();
NOTE:
If you need a string, for example in a blade, you can use function without the toArray() part, like:
test::where('id' ,'>' ,0)->pluck('id');
UPDATE: For versions < 5.2
You could use lists() :
test::where('id' ,'>' ,0)->lists('id')->toArray();
NOTE : Better if you define your models in Studly Case format, e.g Test.
You could also use get() :
test::where('id' ,'>' ,0)->get('id');
From a Collection, another way you could do it would be:
$collection->pluck('id')->toArray()
This will return an indexed array, perfectly usable by laravel in a whereIn() query, for instance.
The correct answer to that is the method lists, it's very simple like this:
$test=test::select('id')->where('id' ,'>' ,0)->lists('id');
Regards!
You can use all() method instead of toArray() method (see more: laravel documentation):
test::where('id' ,'>' ,0)->pluck('id')->all(); //returns array
If you need a string, you can use without toArray() attachment:
test::where('id' ,'>' ,0)->pluck('id'); //returns string
Just an extra info, if you are using DB:
DB::table('test')->where('id', '>', 0)->pluck('id')->toArray();
And if using Eloquent model:
test::where('id', '>', 0)->lists('id')->toArray();
A simple way to get an array with the model IDs from a collection:
$test = test::select('id')->where('id' ,'>' ,0)->get('id')->modelKeys();
Available since Laravel 5.5: https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Collection.html#method_modelKeys
read about the lists() method
$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()
Although you have marked the Answer, This is a much simpler approach
App\User::pluck('id')->toArray()
In Laravel 8 this works for me
$arr = SomeModel::where("field", value)->get()->toArray();

Symfony query wrong result

I'm using a personal request in symfony witch is:
public function findByReferenceUser($Reference, $User)
{
$qb = $this->createQueryBuilder('a')
->select('a')
->join('a.Reference', 'r')
->where('r.id = :refId')
->setParameter("refId", $Reference->getId())
->join('a.User', 'u')
->andWhere('u.id = :userId')
->setParameter("userId", $User->getId());
return $qb->getQuery()->getOneOrNullResult();
}
But it doesn't work properly.
I'm getting 3 results witch are of type NULL,NULL, Boolean. I'm using this to check it:
$list_article = $RArticle->findByReferenceUser($reference, $panier->getUser());
foreach ($list_article as $key => $article)
echo gettype($article);
My database works, and have the right informations.
Finnaly, this works:
$list_article = $RArticle->findAll();
foreach ($list_article as $key => $article)
echo gettype($article);
And print object, object.
So there is my questions: Why do I get NULL, NULL, Boolean in the first case and how do I fixe it?
Thank you for your help! :)
When using getOneOrNullResult, Doctrine will Retrieve a single object. If no object is found null will be returned. here.
If you want several object, you should use getResult
findAll() returns array of objects, such as array('key' => 'object'), that's why you are getting correct records, getOneOrNullResult() returns single object (not array, foreach won't work), if you want to retrieve multiple records you need to use getResult()

PHP Codeigniter Array Calculations

I am having a problem, which I hope someone could help me with.
I am using CodeIgniter to pull results from a database, and I would like to add these results together. I am not much of a PHP developer, so I am not too sure where to start.
This is the function I am using;
function get_warranty($id) {
$this->db->select('warranty');
$this->db->where('sID', $id);
$query = $this->db->get('cars');
return $query->result();
}
This function, returns this;
[warranty] = Array
(
[0] => stdClass Object
(
[warranty] => 2
)
[1] => stdClass Object
(
[warranty] => 5000
)
)
But, I would like it to return this;
[warranty] = 5002;
So, it simply adds up each result it finds.
Any help at all, would be greatly appreciated, as I say, I'm not much of a PHP developer, so I don't even know where to start.
Thanks in advance!
The $query -> result() function returns an array of objects with query results...
See documentation: http://ellislab.com/codeigniter/user-guide/database/active_record.html#select
This is the modified function I propose, which simply returns an integer with the total sum, as you need:
function get_warranty($id) {
// Query composition
$this->db->select('warranty');
$this->db->where('sID', $id);
$query = $this->db->get('cars');
// Iterate through the returned objects and accumulation in $warranty
foreach ($query->result() as $row) {
$warranty += $row->warranty;
}
return $warranty;
}
Kind regards.
In place of return $query->result(); use return $query->result_array();. You will get returned with pure array.
Now you can use foreach loop to add the values up like this:
$add_up = 0;
foreach ($reulst_array as $values)
{
$addup = $add_up + $values;
}
This way variable $add_up will contain the added array.

Categories