通过模型雄辩访问模型列表

时间:2016-10-01 14:20:21

标签: php laravel eloquent

User有许多AuktionGebot
Gebot属于一个Auktion和一个User

我想抓取Auktion也有User

的所有Gebot

类似的东西:

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

orderBy()应该在Auktionen通过Gebot检索后执行,这是不可能的,因为Auktion和Gebot之间的关系是一对多:

  **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');
  }

实现此目的的关系设置和查询是什么?

修改

我目前的做法是这个

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

这不是很干净,因为我首先获取所有条目而且我不能orderBy()

1 个答案:

答案 0 :(得分:1)

使用whereHas()来过滤您的关系的相关性。 Auktion必须与hasMany() 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();