使用模型中的 addSelect 函数添加列时未添加选择字段

发布于 2025-01-21 02:07:52 字数 1383 浏览 0 评论 0原文

因此,我试图包括一个称为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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文