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

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]);
}
);

Related

Laravel acces variable from inside $collection->each() loop [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 1 year ago.
I want build a new collection from an existing collection using an each() loop:
$spot = Spot::where('slug', $slug)->first()->load('features.group');
$test = collect();
$spot->features->each(function ($item, $key) {
$current = collect([
$item->group->name => $item->name,
]);
$test->mergeRecursive($current);
});
dd($test);
I am getting the error Undefined variable $test from the code inside the loop. How can I access the $test collection from inside the loop?
Thanks!
You can pass data inside the closure by use(). Try this:
$spot = Spot::where('slug', $slug)->first()->load('features.group');
$test = collect();
$spot->features->each(function ($item, $key) use(&$test) {
$current = collect([
$item->group->name => $item->name,
]);
$test->mergeRecursive($current);
});
dd($test);

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

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();

How do i get the most recent objects laravel [duplicate]

This question already has answers here:
Laravel: How to get last N entries from DB
(13 answers)
Closed 1 year ago.
How can i make a query to return me the most recent added objects
Controller :
public function __construct()
{
$this->middleware(['auth', 'verified']);
}
public function index(Request $request){
$object = Obj::with('children.objectable', 'ancestorsAndSelf.objectable')->ForTheCurrentTeam()->where(
'uuid', $request->get('uuid', Obj::ForTheCurrentTeam()->whereNull('parent_id')->first()->uuid)
)
->firstOrFail();
return view('home', [
'object' => $object,
'ancestors' => $object->ancestorsAndSelf()->breadthFirst()->get(),
'recent' => $object->orderBy('created_at','desc')->get(),
dd($object),
]);
I am trying to make something like this but for the most recent added objects. How would i do it?
Use latest():
$object = Obj::with('children.objectable', 'ancestorsAndSelf.objectable')->ForTheCurrentTeam()->where(
'uuid', $request->get('uuid', Obj::ForTheCurrentTeam()->whereNull('parent_id')->first()->uuid)
)
->latest()
->firstOrFail();
you can use order by desc and take a specified number of records
'recent' => $object->orderBy('created_at','desc')->take(5)->get()
this will take the 5 latest

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

"IN" and "NOT IN" in CakePHP3 [duplicate]

This question already has answers here:
Access variables from parent scope in anonymous PHP function
(2 answers)
Closed 5 years ago.
There is an example in the Cookbook:
$query = $cities->find()
->where(function ($exp, $q) {
return $exp->notIn('country_id', ['AFG', 'USA', 'EST']);
});
In SQL this should be aequivalent to:
WHERE country_id NOT IN ('AFG', 'USA', 'EST')
Now, I'm trying to use a variable here. Sadly, this won't work:
$query = $cities->find()
->where(function ($exp, $q, $variable) {
return $exp->notIn('country_id', $variable);
});
Any ideas?
I always find the easiest way to use IN and NOT IN is as follows in CakePHP
$query = $cities->find()
->where(['country_id IN' => $variable])
More information on auto generating in clauses is at the following link in the book. You can also use it to cast values to the type of the column automatically. To me it is more readable as well.
https://book.cakephp.org/3.0/en/orm/query-builder.html#automatically-creating-in-clauses
It works with "use", see: PHP: Anonymous Functions
$query = $cities->find()
->where(function ($exp, $q) use ($variable) {
return $exp->notIn('country_id', $variable);
});

Categories