'Select fields not being added when adding columns with the addSelect function from a model
So i am trying to include a custom field called status, created a scope for it so it is reusable. But when adding the field the other fields of the given model aren't being queried.
use Illuminate\Database\Eloquent\Builder;
...
/**
* Scope include something.
*/
public function scopeIncludeSomething(Builder $query): Builder
{
return $query->addSelect(DB::raw('(field_two * field_two) as something'))
}
So when I query the model with some fields selected e.g.:
Model::includeStatus()->get(['field_one', 'field_two']);
Then this is being returned:
[
0 => array:1 [
"something" => 2
]
1 => array:1 [
"something" => 3
]
]
I can add the columns of the model in the addSelect statement, but I want to set them in the get function on the model. So this does work:
use Illuminate\Database\Eloquent\Builder;
...
/**
* Scope include something.
*/
public function scopeIncludeSomething(Builder $query): Builder
{
return $query->addSelect(DB::raw(', (field_one * field_two) as something'))
}
Model::includeStatus()->get(['field_one', 'field_two']);
[
0 => array:3 [
"something" => 16,
"field_one" => 4,
"field_two" => 4
]
1 => array:3 [
"something" => 4,
"field_one" => 2,
"field_two" => 2
]
]
Anyone who knows a solution to this so the get function on the model still selects the columns you pass in it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
