A User
有多个Auktion
和Gebot
。
一个Gebot
属于一个Auktion
和一个User
我想获取所有Auktion
,其中User
也有Gebot
类似:
Auth::user()->gebote->auktionen->orderBy('end_time');
orderBy()应该在通过Gebot
检索的Auktionen
上执行,这是不可能的,因为auction和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()
使用whereHas()
,它将通过它的子关系过滤你的关系。Auktion
必须和hasMany()
有类似的关系
$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();