Laravel query builder combine pluck() with keyBy() [duplicate] - php

This question already has answers here:
Laravel Eloquent Pluck without losing the key
(7 answers)
Closed 1 year ago.
I would like Laravel query-builder to return an array of key => value.
For example, for users table which has columns username, email return something like:
Array
(
[email1] => username1
[email2] => username2
)
Now, I can achieve each one of the with either pluck('username') or with keyBy('email').
I can use php array functions to manipulate result returned by keyBy in order to achieve what I want:
$tmpRes = DB::table('users')
->select(['username', 'email'])
->get()->keyBy('email')->toArray();
$res = array_map(function ($el) {
return $el->username;
}, $tmpRes);
I wonder whether there is a direct way to do so.

Pluck actually allows a second parameter as a key
public static function pluck($column, $key = null)
So all you have to do is pass that in
$tmpRes = DB::table('users')
->pluck('username', 'email')
->toArray();

Related

Laravel count distinct value and get as associative array of key value pair

I have a field called language in my table submission. Here the different user has submitted their problem with different language such as java(56) 5 times, CPP(45) 7 times, and python(71) 10 times.
I want to have a query in laravel with eloquent such that it returns an array or with key-value pair as
$user_lang = ['56'=>5,'45'=>7,'71'=>10]
here 56,45,71 are the id of the languages
If you have prepared data like count of how many times, you can simply use pluck method. eg
$user_lang = Language::where(<condition>)->pluck('times', 'id');
It will return the array as you desired.
If you do not have prepared count, then count it using group by and simply use same pluck method .
$result = Submission::selectRaw('id', 'COUNT(DISTINCT id) AS times'))
->groupBy(id)
->get();
$user_lang = [];
$result->map($result, function($item){
$user_lang[$item->id] = $item->times;
});

Select specific column only from Laravel 5.2 Relation query not working [duplicate]

This question already has answers here:
Get Specific Columns Using “With()” Function in Laravel Eloquent
(19 answers)
Closed 2 years ago.
So I have a query that I only want to get specific columns in a relation but is not working. I'm using Laravel 5.2 by the way. Here's what I have:
$job = Job::query()->whereId($job_id)
->with([
'jobType' => function (Relation $query) {
$query->select(['name']);
},
])
->first();
If I do that, the jobType relationship returns null as seen below:
And if I'll remove the $query->select(['name']);, it has the data from job_type table. How can I just successfully get specific column from a table?
Maybe This can.. To get the specific column you need a specific jobtype
$job = Job::query()->whereId($job_id)
->with(['jobType' => function ($q) use($jobType) {
$q->where(// check the condition on jobtype table);
$q->select(['name']);
},
])
->first();

Is it possible to generate associative array from laravel pluck()

ModalName::pluck('id')->toArray();
i want id to be associative array with certain defined key.
such as 'my_key'=>id in a pluck
First of all pluck() return you already an array so no need to call toArray().
Yes you can make it associative by passing another argument on pluck method. Like this
$plucked = $collection->pluck('name', 'product_id');
sample result
['prod-100' => 'Desk', 'prod-200' => 'Chair']
please see docs here source
so in your case
ModalName::all()->pluck('id', 'name'); // name = field in your table

How to use 'LIKE' in Laravel? [duplicate]

This question already has answers here:
Laravel 'like' query with MongoDB connection
(1 answer)
Laravel-5 'LIKE' equivalent (Eloquent)
(7 answers)
How to query MongoDB with "like"
(45 answers)
Closed 3 years ago.
I'm trying to use 'LIKE' in Laravel. But in the output whole data is displayed. Is my method correct? If not then correct me.
$this->uses('Data');
$a ='nan';
$options = ['sort' => ['city' => 1]];
$results = $this->Part->find([],['city','LIKE',"%$a%"],$options);
return view('testEnv')->with('results',$results);
}
Query Builder
$data = DB::table('table_name')->where('col_name','LIKE','%'.$variable.'%')->get();
"%$a%" is a string ....
You can use where like
$users = DB::table('users')
->where('name', 'like', 'T%')
->get();
Read documentation here

CakePhp - how to access variables inside find->innerJoinWith? [duplicate]

This question already has answers here:
PHP variables in anonymous functions
(2 answers)
Closed 7 years ago.
I am trying to query for users that are assigned to a certain project in CakePHP. How could I basically achieve this:
$projectId = //Project ID query result.
$users = $this->Tickets->Users
->find('list', ['limit' => 200])
->innerJoinWith(
'ProjectsUsers', function($q){
return $q->where(['ProjectsUsers.project_id' => $projectId]);
}
);
This code works when not using variables (eg. replacing $projectId with 8) but when I try to use variables I get: Undefined variable: projectId
How can I pass variables into innerJoinWith?
If you mean how to inherit a variable from the parent scope, you'd do it like this.
$users = $this->Tickets->Users
->find('list', ['limit' => 200])
->innerJoinWith(
'ProjectsUsers', function($q) use($variableToPass) {
return $q->where(['ProjectsUsers.project_id' => $variableToPass]);
}
);

Categories