向所有 eloquent 个查询结果添加一些记录
Add some records to all eloquent query results
我有一个名为 food_portion 的 table,如下所示:
id|food_id|name|gram_weight
1|102030|slice|183
2|102030|pie|183
3|102031|waffle|35
....
table 是完整的,但是缺少一些全局部分,例如 gram/oz..
我想编写一个查询来为这部分添加记录,但我认为这不是一个好的选择,因为这部分对所有食物都具有相同的价值。
*|*|gr|1 (6000 records like this)
*|*|oz|28 (and another 6000 like this)
所以我正在寻找一种方法来修改我的模型 (food_portion),所以每次我使用模型执行一些查询时,都会获取上述记录,而无需将它们物理存储在数据库中 table ,所以我的查询不会无缘无故变慢。
我该怎么做。我尝试使用全局范围执行此操作但我失败了:
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?
});
});
}
底线是我想防止每种食物的记录重复。
我想在每个查询结果中添加两条特定的记录。
提前致谢
我觉得你很亲近,看看这个:
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();
我有一个名为 food_portion 的 table,如下所示:
id|food_id|name|gram_weight
1|102030|slice|183
2|102030|pie|183
3|102031|waffle|35
....
table 是完整的,但是缺少一些全局部分,例如 gram/oz.. 我想编写一个查询来为这部分添加记录,但我认为这不是一个好的选择,因为这部分对所有食物都具有相同的价值。
*|*|gr|1 (6000 records like this)
*|*|oz|28 (and another 6000 like this)
所以我正在寻找一种方法来修改我的模型 (food_portion),所以每次我使用模型执行一些查询时,都会获取上述记录,而无需将它们物理存储在数据库中 table ,所以我的查询不会无缘无故变慢。
我该怎么做。我尝试使用全局范围执行此操作但我失败了:
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?
});
});
}
底线是我想防止每种食物的记录重复。 我想在每个查询结果中添加两条特定的记录。
提前致谢
我觉得你很亲近,看看这个:
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();