Pages

13 July, 2020

How to use condition for one to many relationship in Laravel

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

No comments:

Post a Comment

Thanks