drux41001 2016-10-01 06:20
浏览 55
已采纳

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

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()

展开全部

  • 写回答

1条回答 默认 最新

  • duancheng8000 2016-10-01 06:44
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?