Reputation: 65
In eloquent we can using anonymous functions as second parameter in where method. i want to use a non-anonymous class method instead of it. but doesn't work for me.
regular anonymous mode: (working old style) - I don't want to use this method
->whereIn('plantation_id', function ($query) use ($plantationId){
$query->select('id')
->from('plantations')
->whereBetween('_lft', [
DB::raw('(SELECT `_lft` FROM `plantations` WHERE id = ' . $plantationId .')'),
DB::raw('(SELECT `_rgt` FROM `plantations` WHERE id = '. $plantationId .')')
]);
});
I want to use:
Query:
->whereIn('plantation_id', Plantation::getIdsByParent($query, $plantationId));
Plantation Class:
class Plantation extends Model
{
....
public static function getIdsByParent($query, $plantationId)
{
return $query->select('id')
->from('plantations')
->whereBetween('_lft', [
DB::raw('(SELECT `_lft` FROM `plantations` WHERE id = ' . $plantationId .')'),
DB::raw('(SELECT `_rgt` FROM `plantations` WHERE id = '. $plantationId .')')
]);
}
}
Upvotes: 0
Views: 458
Reputation: 153
Can you post the error you get?
As far as i understand it you want to get a Collection/Array of id's with your getIdsByParent.
My understanding would be you that your function returns a QueryBuilder instance to return a collection you would need to add a ->get() at the end. Does this work for you:
public static function getIdsByParent($query, $plantationId)
{
return $query->select('id')
->from('plantations')
->whereBetween('_lft', [
DB::raw('(SELECT `_lft` FROM `plantations` WHERE id = ' . $plantationId .')'),
DB::raw('(SELECT `_rgt` FROM `plantations` WHERE id = '. $plantationId .')')
])->get();
}
If you want to have an array a simple ->toArray() at the end should do.
Also maybe using a Query Scope for this does the trick.
Upvotes: 0
Reputation: 2745
If you don't want to duplicate code you can do:
->whereIn('plantation_id', function($query) use ($plantationId) {
return Plantation::getIdsByParent($query, $plantationId);
});
Still has an anonymous function but you are making use of your already defined logic without copy-pasting it.
Upvotes: 1