4ndro1d 4ndro1d - 2 months ago 13
PHP Question

Eloquent access list of models via models

A

User
has many
Auktion
and
Gebot
.

A
Gebot
belongs to one
Auktion
and one
User


I want to fetch all
Auktion
where the
User
also has a
Gebot


Something like:

Auth::user()->gebote->auktionen->orderBy('end_time');


The orderBy() should be executed on the
Auktionen
retreived via
Gebot
, which is not possible because the relationship between Auktion and Gebot is one-to-many:

**Gebot Model**
public function auktion()
{
return $this->belongsTo('App\Auktion');
}


public function user()
{
return $this->belongsTo('App\User');
}

**Auktion Model**
public function gebote()
{
return $this->hasMany('App\Gebot', 'auktion_id');
}

public function user()
{
return $this->belongsTo('App\User');
}


What is the proper relationshsip setup and query to achieve this?

EDIT:

My current approach is this

@foreach (Auth::user()->gebote as $gebot)
<?php $auktion = $gebot->auktion;
if($auktion->anzeigentyp_id == 2)
continue; ?>
@include('shop/row')
@endforeach


which is not very clean as I am fetching all entries first and I can't
orderBy()

Answer

Use whereHas() which will filter your relation by it's subrelation. Auktion must have relation smth like hasMany() to gebots

$userId = Auth::user()->getKey();
App\Auktion::whereHas('gebot', function ($query) use($userId) {
    //here you need to filter gebots which belongs to user
    $query->where('user_id', $userId);
})->orderBy('end_time')->get();
Comments