【问题标题】:How to use condition for one to many relationship in Laravel如何在 Laravel 中为一对多关系使用条件
【发布时间】:2015-10-26 04:44:52
【问题描述】:

我正在使用 Laravel 4.2

我有以下型号: UserBooking(booking 的 user_id 引用了 id 中的 User 模型)

我想进行查询以检索 Bookings where bookings.starts_at > now

我想要这样的东西:

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

但是 where 条件应用于用户,因此会导致异常,因为用户没有starts_at。

如何在仍然使用 Eloquent 类的同时解决这个问题?

谢谢

【问题讨论】:

    标签: php database laravel laravel-4


    【解决方案1】:

    这在控制器中:

    加载表用户和表预订加入 user_id where 'bookings.starts_at'>' 2015-07-04'。

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

    将模型放入 Models 文件夹中。

    用户模型:

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

    【讨论】:

    • 非常感谢。这回答了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    相关资源
    最近更新 更多