Home > Back-end >  Add some records to all eloquent query results
Add some records to all eloquent query results

Time:12-14

I have a table named food_portion like the following:

id|food_id|name|gram_weight


1|102030|slice|183

2|102030|pie|183

3|102031|waffle|35

....

The table is complete, But some global portions are missing like gram/oz.. I wanted to write a query to add records for this portions but I'm thinking that its not a good choice because this portions have same value for all the foods.

*|*|gr|1 (6000 records like this)

*|*|oz|28 (and another 6000 like this)

So I'm looking for a way to modify my model (food_portion) so every time I execute some query using model get the the above records without having them physically in the database table, So my queries wouldn't be slow for no reason.

How can I do this. I tried to do this using global scope but I failed:

 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?
        });
        });
    }

Bottom line is I want to prevent record repetition for every food. I want to add two specific records to every query result.

Thanks in advance

CodePudding user response:

I think you are very close, check this:

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"),
            ]));
        });
    }

This is to add one record. To add more, simply chain more union functions, or edit the query inside.

Note: For Laravel 6.x use "boot" instead of "booted", and add a line parent::boot(); before addGlobalScope

  • Related