我有一個名為 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?
});
});
}
底線是我想防止每種食物重復記錄。我想為每個查詢結果添加兩條特定記錄。
提前致謝
uj5u.com熱心網友回復:
我認為你很接近,檢查這個:
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”,并parent::boot();在前面添加一行addGlobalScope
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/380517.html
下一篇:多個按資料分組Laravel
