doufu5521 2015-10-27 04:45
浏览 94
已采纳

Laravel Eloquent另一个表中的列的总和

so I have this output:

enter image description here

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:

enter image description here

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

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.

  • 写回答

1条回答 默认 最新

  • douwei2966 2015-10-27 08:56
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?