【问题标题】:Add some records to all eloquent query results为所有 eloquent 查询结果添加一些记录
【发布时间】:2022-01-16 18:03:15
【问题描述】:

我有一个名为 food_portion 的表,如下所示:

id|food_id|name|gram_weight


1|102030|切片|183

2|102030|派|183

3|102031|华夫饼|35

....

表格是完整的,但是缺少一些全局部分,例如克/盎司.. 我想编写一个查询来为这部分添加记录,但我认为这不是一个好的选择,因为这部分对所有食物都有相同的价值。

*|*|gr|1(6000 条这样的记录)

*|*|oz|28(还有另外 6000 个这样的)

所以我正在寻找一种方法来修改我的模型 (food_portion) 所以每次我使用模型执行一些查询时都会获取上述记录,而不会将它们物理地放在数据库表中,所以我的查询不会很慢没有理由。

我该怎么做。我尝试使用全局范围执行此操作,但失败了:

 protected static function booted()
    {
        static::addGlobalScope('global_portions', function (Builder $builder) {
        $builder->orWhere( function($query)
        {
            //$query->where("food_id","*")->where("name","gr") ???
            // what should I write here?
        });
        });
    }

底线是我想防止每种食物的记录重复。 我想为每个查询结果添加两条特定记录。

提前致谢

【问题讨论】:

  • 感谢您的关注,是的,我有很多。但它们是用于添加列而不是记录
  • 对不起,如果我弄错了,您想在查询结果中添加更多行吗?例如,如果您查询了 10 条结果,您会想要再添加 100 条,这样您就可以得到 110 条记录?
  • 只有两条记录

标签: laravel model


【解决方案1】:

我认为你很接近,检查一下:

use Illuminate\Support\Facades\DB;


protected static function booted()
    {
        static::addGlobalScope('global_portions', function (\Illuminate\Database\Eloquent\Builder $builder) {
            $builder->union(DB::query()->select([
                DB::raw("\"*\" AS id"),
                DB::raw("\"*\" AS food_id"),
                DB::raw("\"gr\" AS name"),
                DB::raw("\"1\" AS gram_weight"),
            ]));
        });
    }

这是添加一条记录。要添加更多,只需链接更多 union 函数,或编辑其中的查询。

注意:对于 Laravel 6.x,请使用“boot”而不是“booted”,并在 addGlobalScope 之前添加一行 parent::boot();

【讨论】:

    猜你喜欢
    • 2019-11-04
    • 2023-03-23
    • 2023-03-07
    • 1970-01-01
    • 2020-10-18
    • 2016-04-30
    • 1970-01-01
    • 2021-10-10
    • 2023-03-28
    相关资源
    最近更新 更多