使用模型中的 addSelect 函数添加列时未添加选择字段
因此,我试图包括一个称为status
的自定义字段,为其创建一个范围,以便它可以重复使用。但是,当添加字段时,给定模型的其他字段不会被查询。
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'))
}
因此,当我使用选定的某些字段查询模型时:
Model::includeStatus()->get(['field_one', 'field_two']);
然后将其返回:
[
0 => array:1 [
"something" => 2
]
1 => array:1 [
"something" => 3
]
]
我可以在AddSelect语句中添加模型的列,但是我想在模型上的GET函数中设置它们。因此,这确实有效:
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
]
]
任何了解此解决方案的人,因此模型上的GET功能仍然选择您传递的列。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论