mercredi 9 août 2017

Where clause on a model relation

I want to eager load locales with items- but only want to load items with locale of a specified value.

I.e., If the current locale is set to ID 2, I want all items with locale ID 2 in its related table item_locale.

How can I do this?

public function locales($localeId)
{
    return $this->belongsToMany(Locale::class, 'item_locale')
        ->withPivot('target')
        ->where('locale', $localeId); // <-- how can I accomplish this?
}


User Controller:

return $userGameProfile = User::with(
    [
        ...
        'items' => function($query) use ($profile_id) {
            $query->where('profile_id', '=', $profile_id);
        },
        ...
    ]
)->find($id);

...

User Model:

class User extends Model ...
{
    public function items()
    {
        return $this->belongsToMany(Item::class, 'user_item')
            ->withPivot('item_count');
    }
    ...

Item Model:

class Item extends Model
{
    protected $with = [..., 'locales'];

    public function locales($localeId)
    {
        return $this->belongsToMany(Locale::class, 'item_locale')
            ->withPivot('target')
            ->where('locale', $localeId);
    }
}

Locale Model:

class Locale extends Model
{
    ...
    public function items()
    {
        return $this->belongsToMany(Item::class);
    }
}

item_locale table:

   item_id | locale_id | target
        1         1         狗  // don't want these results
        1         2         dog // only want result of locale ID 2



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire