簡體   English   中英

如何在Laravel中使用一對多關系的條件

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

我正在使用Laravel 4.2

我有以下模型: 用戶預訂 (預訂具有在id中引用用戶模型的user_id)

我想查詢一個預訂信息,以便在bookings.starts_at>現在

我想要這樣的東西:

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

但是條件應用於用戶,因此會導致異常,因為用戶沒有starts_at。

在仍然使用Eloquent類的同時如何解決此問題?

謝謝

這在控制器中:

加載表用戶和表預訂已在user_id上加入,其中“ bookings.starts_at'>'2015-07-04”。

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

將模型放入“模型”文件夾。

用戶模型:

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

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

預訂模型

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