Laravel Eloquent 另一个表中列的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33360122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent sum of column in another table
提问by wobsoriano
so I have this output:
所以我有这个输出:
Here is the code in my controller:
这是我的控制器中的代码:
public function showToday()
{
$now = new DateTime('today');
$today = $now->format('Y-m-d');
$reservations = Reservation::with('room') ->where('reservation_from', $now)
->orderBy('created_at')
->get();
return \View::make('pages.admin.report.today') -> with('reservations', $reservations)
-> with('now', $today);
}
Schema:
架构:
View (blade)
视图(刀片)
<div class="box-body table-responsive no-padding">
<table class="table table-bordered">
<thead>
<tr>
<th>Room #</th>
<th>Reservation From</th>
<th>Reservation To</th>
<th>Booked At</th>
<th>Amount</th>
</thead>
</tr>
<tbody>
@foreach($reservations as $res)
<tr>
<td>{{ $res -> room -> room_number }}</td>
<td>{{ date('F d, Y', strtotime($res -> reservation_from)) }}</td>
<td>{{ date('F d, Y', strtotime($res -> reservation_to)) }}</td>
<td>{{ $res -> created_at }}</td>
<td>{{ $res -> room -> price }}</td>
</tr>
@endforeach
<tr>
<td colspan="2"><strong>Total:</strong></td>
<td></td>
<td></td>
<td></td>
<td><!-- Display price total here --></td>
</tr>
</tbody>
</table>
</div>
Reservation Model
预订模式
class Reservation extends Model
{
use SoftDeletes;
protected $table = 'reservations';
protected $fillable = ['roomNumber', 'clientId', 'reservation_from', 'reservation_to'];
public function room() {
return $this->belongsTo('App\Room');
}
}
Room model
房间模型
class Room extends Model
{
use SoftDeletes;
protected $table = 'rooms';
protected $fillable = ['id', 'roomNumber', 'type', 'price', 'description'];
public function reservations() {
return $this->hasMany('App\Reservation', 'id', 'room_number');
}
}
When I try to add this in my controller,
当我尝试在我的控制器中添加它时,
$sum = $reservations['room']->sum( 'price' );
dd($sum);
I get an Undefined index: room
我得到一个 Undefined index: room
What I wanted to is to display the total amount(sum) by adding the prices from the rooms table. How can I do that with Laravel and Eloquent? Thank you in advance.
我想要的是通过添加房间表中的价格来显示总金额(总和)。我怎么能用 Laravel 和 Eloquent 做到这一点?先感谢您。
回答by Iamzozo
$reservations->sum('room.price')
$reservations->sum('room.price')