2015-10-27 5 views
3

поэтому у меня есть этот выход:Laravel Eloquent сумма столбца в другой таблице

enter image description here

Вот код в мой контроллер:

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); 
    } 

Схема:

enter image description here

View (лезвие)

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

Бронирование Модель

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'); 
    } 

} 

модель номер

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'); 
    } 
} 

Когда я пытаюсь добавить это в мой контроллер,

$sum = $reservations['room']->sum('price'); 
dd($sum); 

я получаю Undefined index: room

То, что я хотел, чтобы отобразить общее количество (сумма), добавив цены из таблицы номеров. Как я могу это сделать с Laravel и Eloquent? Заранее спасибо.

+0

Что соотношение между бронированием и комнаты? Какое первое изображение вы нам показываете? вам нужно объяснить, была ли это другая таблица базы данных или просто представление. сделайте свой вопрос понятным \ –

+0

Почему бы просто не суммировать на ваш взгляд? Подобно define '$ total = 0' перед вашим циклом, а затем в вашем foreach' $ total + = $ res-> room-> price'. – Iamzozo

ответ

4

$reservations->sum('room.price')

+0

Также новичок ко мне :) – Iamzozo

+0

Попробуй это немного – FewFlyBy

+0

Странно, я протестировал. Проверьте его снова. – Iamzozo