【问题标题】:Laravel Eloquent sum of column in another tableLaravel Eloquent 另一个表中列的总和
【发布时间】:2015-10-27 04:45:34
【问题描述】:

所以我有这个输出:

这是我的控制器中的代码:

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

架构:

查看(刀片)

  <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 做到这一点?提前谢谢你。

【问题讨论】:

  • 您的预订和房间有什么关系?你给我们看的第一张图片是什么?您需要解释这是另一个数据库表还是只是一个视图。把你的问题说清楚\
  • 为什么不简单地总结一下你的观点呢?就像在循环之前定义 $total = 0 一样,然后在 foreach 中定义 $total += $res-&gt;room-&gt;price。

标签: php laravel laravel-5


【解决方案1】:

$reservations-&gt;sum('room.price')

【讨论】:

  • 一会儿试试这个
  • 奇怪,我测试过。再检查一遍。
  • 让我再试一次,我的数据库好像出错了
  • 完美!谢谢!
  • 太棒了。谢谢你!
猜你喜欢
  • 1970-01-01
  • 2015-08-01
  • 2020-06-06
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 2017-02-16
  • 2021-09-04
  • 2020-05-31
相关资源
最近更新 更多