简体   繁体   English

如何在Laravel中使用一对多关系的条件

[英]How to use condition for one to many relationship in Laravel

I am using Laravel 4.2 我正在使用Laravel 4.2

I have the following models: User and Booking (booking has user_id that references User model in id) 我有以下模型: 用户预订 (预订具有在id中引用用户模型的user_id)

I want to make a query to retrieve Bookings where bookings.starts_at > now 我想查询一个预订信息,以便在bookings.starts_at>现在

I want something like this: 我想要这样的东西:

User::with('bookings')->where('starts_at' , '>' time())->get();

but where condition is applied on User and hence it causes an exception because User does not have starts_at. 但是条件应用于用户,因此会导致异常,因为用户没有starts_at。

How to solve this issue while still using Eloquent class? 在仍然使用Eloquent类的同时如何解决此问题?

Thanks 谢谢

This in controller: 这在控制器中:

Load table user and table bookings joined on user_id where ' bookings.starts_at '>' 2015-07-04 '. 加载表用户和表预订已在user_id上加入,其中“ bookings.starts_at'>'2015-07-04”。

User::with(['bookings'=>function($query){
            $query->where('starts_at' , '>', date('Y-m-d'));
          }])->get();

Put your models into Models folder. 将模型放入“模型”文件夹。

Model for user: 用户模型:

class User extends Eloquent {
     protected $table = 'users';
     protected $fillable = array('name','last_name');

  public function bookings() {
      return $this->hasMany('Bookings', 'user_id');
  }
}

model for bookings 预订模型

start_at format should be year: month : date start_at格式应为年:月:日期

class Bookings extends Eloquent {

  protected $table = 'bookings';
  protected $fillable = array('id','booking','user_id','start_at');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM