drux41001 2016-10-01 14: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 14: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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据