How to use condition for one to many relationship in Laravel

馋奶兔 提交于 2020-01-01 17:52:07

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/31798095/how-to-use-condition-for-one-to-many-relationship-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!