How to Do following Query in Laravel Eloquent?
SELECT catID, catName, imgPath FROM categories WHERE catType = "Root"
I have tried following
CategoryModel::where('catType', '=', 'Root')
->lists('catName', 'catID', 'imgPath');
but its return only two fields.
Array ( [7] => Category 1 )
lists() turns the resulting collection into an array with key value. You can only have two database columns in there. Otherwise you have to use select() but then you will get a collection of models not just an array.
$categories = CategoryModel::select('catID', 'catName', 'imgPath')
->where('catType', '=', 'Root')
->get();
Selecting multiple columns
CategoryModel::get(['catName', 'catID', 'imgPath']);
Works with Laravel 5.3 too!
If you want to get certain columns then You can use one of the two method get() or all()
but the syntax is different for both, get() method takes array as argument and all() method takes string or array both as argument:
Model::all('field1','field2') with string as arguments
CategoryModel::all('catName', 'catID', 'imgPath')->where('catType','Root');
Model::all(['field1','field2']) with array as arguments
CategoryModel::all(['catName', 'catID', 'imgPath'])->where('catType','Root');
Model::get(['field1','field2'])
CategoryModel::get(['catName', 'catID', 'imgPath'])->where('catType','Root');
CategoryModel::wherecatType('Root')
->pluck('catName', 'catID', 'imgPath');
From laravel version 5.3^ lists() is deprecated and function pluck() is used instead.
pluck() returns a collection and if you need a simple array just prepend ->toArray() to it.
Related
I got an error in
Call to a member function first() on double
this is query builder in laravel
$player = DB::table('players')
->join('stats', 'players.username', '=', 'stats.player')
->sum('stats.winpot');
->first();
of course. it's obvious. the sum() function return sum of the selected column. a single value (not a collection of values)
the first() is for Collections, to get the first element from a collection.
Since the sum function returns the sum of the column values (A single value, not a Collection), you cant call first() function on it.
And Most importantly You Don't Have To.
NOTE
If you want to get both 'player' and the 'sum' you can execute two queries and bind those two results together.
Possible solution.
$player = DB::table('players')
->join('stats', 'players.username', '=', 'stats.player')
->first();
$player->sum = DB::table('players')
->join('stats', 'players.username', '=', 'stats.player')
->sum('stats.winpot');
now there is an attribute in retrieved 'player' as 'sum'. you can access it as $player->sum
I solver this by this code
$service_list = Service::all();
$services = [];
foreach ($service_list as $item){
$services[$item['id']] = $item['name'];
}
but how to do that using php_array functions?
its for dropdown select
Not sure why you have to use PHPs built in array methods but we have pluck on the Query Builder and Collection class.
$services = Service::pluck('name', 'id');
// $services->all(); // for the actual array contained
This will only select the name and id in the query and give you a Collection keyed by the id only containing the name field.
$services = Service::all();
$services_array = $services->pluck('name', 'id')->all();
If you already have your collection of models (code above has queried for every field and hydrated models with the result) you can use pluck on the Collection to achieve the same result (though less efficient as it had to query for all fields, hydrate models, then pull those 2 fields from them)
Laravel 5.5 Docs - Query Builder - Retrieving Results
Laravel 5.5 Docs - Collections - pluck method
Use toArray() to convert the collection to an array, then use array_combine() to create an associative array from that.
$service_list = Service::all()->toArray();
$services = array_combine(array_column($service_list, 'id'), array_column($service_list, 'name'));
$service_list = Service::all()->toArray();
all() will return a collection. The collection supports a toArray() method
Can I select value from relationships with function "with" ?
So make something like this:
$test = User::where('id',1)->with(['user_detail' => function($query){
$query->select("detail_1");
}])->get();
Yes I know that I can put select in relation "user_detail" but can I select in with function?
You can select within with as you made the example given below:
$test = User::where('id',1)->with(['user_detail' => function($query){
$query->select("detail_1");
}])->get();
But it won't not work (as you commented in other answer) because you've only selected a single property but the foreign key is not available in your select statement. So, make sure that, you also select the related foreign key as well and then it'll work.
In your case, I believe that, you've to also select the user_id in your select for example:
$test = User::where('id',1)->with(['user_detail' => function($query){
$query->select(
'user_id', // This is required if this key is the foreign key
'detail_1'
);
}])->get();
So, without the foreign key that makes the relation, Eloquent won't be able to load the related models and that's why you get null in your result as you mentioned in other comment.
Yes, you can use select() inside with(). Just pass an array of columns:
$query->select(['detail_1', 'detail_2']);
Alternatively, you can create another relation and add select() to it:
public function userDatails()
{
return $this->hasMany('App\UserDetail')->select(['detail_1', 'detail_2']);
}
$result = Staff::where('live_status',2)
->with('position')->with('department')->with('gender')
->with(['partner' => function($query){
$query->where('alive',0);
}]);
I'm trying to upgrade my project L5.1 -> L5.2. In upgrade guide there's one thing which isn't clear for me:
The lists method on the Collection, query builder and Eloquent query
builder objects has been renamed to pluck. The method signature
remains the same.
That's ok, rename refactoting from lists() to pluck() isn't a problem. But what with useful pluck() method which was in L5.0 and L5.1?
From the 5.0 documentation:
Retrieving A Single Column From A Row
$name = DB::table('users')->where('name', 'John')->pluck('name');
What is the alternative for old pluck() method in L5.2?
UPDATE:
Example:
var_dump(DB::table('users')->where('id', 1)->pluck('id'));
L5.1:
// int(1)
L5.2:
// array(1) { [0]=> int(1) }
The current alternative for pluck() is value().
In Laravel 5.1+, you can use the value() instead of pluck.
To get first occurence, You can either use
DB::table('users')->value('name');
or use,
DB::table('users')->where('id', 1)->pluck('name')->first();
laravel pluck returns an array
if your query is:
$name = DB::table('users')->where('name', 'John')->pluck('name');
then the array is like this (key is the index of the item. auto incremented value):
[
1 => "name1",
2 => "name2",
.
.
.
100 => "name100"
]
but if you do like this:
$name = DB::table('users')->where('name', 'John')->pluck('name','id');
then the key is actual index in the database.
key||value
[
1 => "name1",
2 => "name2",
.
.
.
100 => "name100"
]
you can set any value as key.
I use laravel 7.x and I used this as a workaround:->get()->pluck('id')->toArray();
it gives back an array of ids [50,2,3] and this is the whole query I used:
$article_tags = DB::table('tags')
->join('taggables', function ($join) use ($id) {
$join->on('tags.id', '=', 'taggables.tag_id');
$join->where([
['taggable_id', '=', $id],
['taggable_type','=','article']
]);
})->select('tags.id')->get()->pluck('id')->toArray();
In the original example, why not use the select() method in your database query?
$name = DB::table('users')->where('name', 'John')->select("id");
This will be faster than using a PHP framework, for it'll utilize the SQL query to do the row selection for you. For ordinary collections, I don't believe this applies, but since you're using a database...
Larvel 5.3: Specifying a Select Clause
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();