【发布时间】:2018-06-26 13:26:43
【问题描述】:
我想在下表中显示有关会议中最后注册的一些信息。此表显示,例如,最后一次注册是由 John 完成的,并且是一个有 2 名参与者的注册,注册的总价值是 10.00。
User that did the registration | Quantity of participants registered | Total Value
John 2 10.00$
Jake 1 5.00$
我有一个显示上述结果的查询:
SELECT users.name,COUNT(participants.registration_id),SUM(registration_types.price)
FROM participants
INNER JOIN registration_types
on participants.registration_type_id =
registration_types.id
INNER JOIN registrations
on registrations.registration_id =
participants.registration_id
INNER JOIN users
on users.id = registrations.user_that_did_registration
group by users.name
但我想使用 Eloquent 进行查询,这样就可以在表格的前列中显示结果:
<table class="table table-striped table-responsive-sm box-shaddow">
<thead>
<tr>
<th scope="col">User that did registration</th>
<th scope="col">Quantity</th>
<th scope="col">Date</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
<tr>
...
</tr>
</tbody>
</table>
使用 Eloquent,我喜欢下面的内容,但它不起作用。您知道查询应该如何在表格中显示必要的数据吗?
$registrationsInfo = Participant::
leftJoin('registration_types', 'participants.registration_type_id', '=', 'registration_types.id')
->leftJoin('registrations', 'registration.id', '=', 'participants.registration_id')
->leftJoin('users', 'users.id', '=', 'registrations.user_that_did_registration')
->selectRaw('users.name, count(participants.registration_id), sum(registration_types.price)')
->groupBy('users.name')
->get();
问题的相关模型:
用户模型:
public function registrations(){
return $this->hasMany('App\Registration','user_that_did_registration');
}
注册模式:
// user that did the registration
public function customer(){
return $this->belongsTo(User::class, 'user_that_did_registration', 'id');
}
public function participants(){
return $this->hasMany('App\Participant');
}
public function conference(){
return $this->belongsTo('App\Conference');
}
会议模型:
public function registrations(){
return $this->hasMany('App\Registration', 'conference_id');
}
参与者模式:
public function registration(){
return $this->belongsTo('App\Registration');
}
public function registration_type(){
return $this->belongsTo('App\RegistrationType');
}
注册类型模型:
class RegistrationType extends Model
{
public function conference(){
return $this->belongsTo('App\Conference');
}
public function participants(){
return $this->hasMany('App\Participant');
}
public function registrations(){
return $this->belongsToMany('App\Registration', 'registration_registration_types');
}
}
【问题讨论】: