hadikm.sh
hadikm.sh

Reputation: 1

How to add constrain to eager load in laravel model

I use $with property in model for eager loading relations and now i need to add constrain to eager load. how can i do that?

simple eager load:

class Category extends Model
{

    protected $table = 'categories';

    protected $fillable = ['slug', 'lang','category', 'complex_id'];

    protected $with = ['items'];

}

what i want to do is something like this:

class Category extends Model
{
    protected $table = 'categories';

    protected $fillable = ['slug',  'lang', 'category', 'complex_id'];

    protected $with = ['items' => function ($q) {
        $q->where('lang', 'en');
    }];
}

but this not allowed in php and i get "Constant expression contains invalid operations" exception.

it is also possible to add an other relation like:

public function englishItems()
{
     return $this->hasOne('App\Item', 'category_id')->where(['lang' => 'en']);
}

and use it in $with property but in this way relation name is changed and we have to create a relation per language and some other problem.

thanks.

Upvotes: 0

Views: 449

Answers (1)

Kevin Bui
Kevin Bui

Reputation: 3045

I reckon you want to eager load english items every time you get categories.

I think this is a perfect use case for global scope:

https://laravel.com/docs/5.8/eloquent#global-scopes

So in the Category model you could define something like this:

class Category extends Model
{
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('withEnglishItems', function (Builder $builder) {
                $builder->with(['items' => function ($query) {
                    $query->where('lang', 'en');
                }]);
        });
    }
}

Upvotes: 1

Related Questions