简体   繁体   中英

How to use condition for one to many relationship in Laravel

I am using Laravel 4.2

I have the following models: User and Booking (booking has user_id that references User model in id)

I want to make a query to retrieve Bookings where bookings.starts_at > now

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.

How to solve this issue while still using Eloquent class?

Thanks

This in controller:

Load table user and table bookings joined on user_id where ' 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

class Bookings extends Eloquent {

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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