如何在Laravel中使用一对多关系的条件 [英] How to use condition for one to many relationship in Laravel

查看:294
本文介绍了如何在Laravel中使用一对多关系的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 4.2

I am using Laravel 4.2

我有以下型号: 用户预订(预订的user_id引用了ID中的用户模型)

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

我想查询现在的bookings.starts_at>的预订

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

我想要这样的东西:

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

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

but where condition is applied on User and hence it causes an exception because User does not have starts_at.

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

How to solve this issue while still using Eloquent class?

谢谢

推荐答案

这在控制器中:

在user_id上加入加载表用户和表预订,其中'bookings.starts_at'>'2015-07-04'.

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.

用户模型:

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

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

预订模型

start_at格式应为年:月:日期

start_at format should be year: month : date

class Bookings extends Eloquent {

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

这篇关于如何在Laravel中使用一对多关系的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆