jeudi 19 juillet 2018

Laravel 5: Eloquent relationship method with conditions

Normal relationship methods don't usually have a condition, and tend to look like this:

class Foo extends Model
{
    public function user()
    {
         return $this->belongsTo(Bar::class, 'a_id');
    }
}

In my model I have a condition in the relationship method like so:

class Foo extends Model
{
    public function user()
    {
        if ($this->type === 'a') {
            return $this->hasOne(Bar::class, 'a_id');
        } else {
            return $this->hasOne(Bar::class, 'b_id');
        }
    }
}

Does Laravel support conditional relationships in Eloquent like above. A lot of the usual methods still work like so:

Foo::get()->first()->user;
Foo::get()->first()->user()->get();

But would the following work predictably:

Foo::with('user')->get();

The issue here is that I am unsure in how the "with" operator works in Eloquent internally.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire