如何将联接查询转换为laravel eloquent查询

时间:2017-05-31 04:24:45

标签: php mysql laravel

我有像这样查询bulider的查询

$schedule = DB::table('users')
        ->join('tblHomeCourts','users.homeCourtId','tblHomeCourts.homeCourtId')
        ->join('tblUserHomeCourts','tblUserHomeCourts.userId','users.userId')
        ->join('tblSchedules','tblUserHomeCourts.userHomeCourtId','tblSchedules.userHomeCourtId')
        ->select('tblHomeCourts.homeCourtName', 'tblHomeCourts.address','tblSchedules.timeFrom','tblSchedules.timeTo','tblSchedules.duration','tblSchedules.scheduleStatus','users.firstName','users.lastName','users.profilePic','users.userId')
        ->where(['tblSchedules.scheduleStatus'=> 0,
        ])->where('timeFrom','>',$request->currentTime)
        ->where('timeTo','>',$request->currentTime)
        ->where('tblUserHomeCourts.homeCourtId',$homeCourtId)
        ->get();

现在,我希望使用雄辩的关系将其转换为适当的雄辩查询我完全搞砸了关系,有人可以帮助我找出解决方案吗?

谢谢:)

1 个答案:

答案 0 :(得分:0)

为实现这一目标,我们必须首先在相关表中定义关系。然后我们需要使用with方法加载联合表。

例如,用户模型应如下所示:

class User extends Model{
  protected $table = 'users';

  public function homeCourt(){
    //Many to one relation between user and homeCourt
    return $this->belongsTo(HomeCourt::class, 'homeCourtId', 'homeCourtId');
  }

  public function userHomeCourts(){
    //One to many relation between user nad userHomeCourt
    return $this->hasMany(UserHomeCourts::class, 'userId', 'userId');
  }
}

您的HomeCourt模型应如下所示:

public class HomeCourt extends Model{
  protected $table = 'tblHomeCourts';

  public function user(){
    //One to many relation between homeCourt and user
    return $this->hasMany(User::class, 'homeCourtId', 'homeCourtId');
  }
}

您的UserHomeCourt模型应如下所示:

public class UserHomeCourt extends Model{
  protected $table = 'tblUserHomeCourts'

  public function user(){
    //Many to one relation between userHomeCourts and users
    return $this->belongsTo(User::class,  'userId', 'userId');
  }

  public function schedules(){
     //One to many relation between userHomeCourts and schedule
     return $this->hasMany(Schedule::class, 'userHomeCourtId', 'userHomeCourtId');
  }
}

您的日程安排模型应如下所示:

public function Schedule extends Model{
  protected $table = 'tblSchedules';

  public function userHomeCourt(){
    //Many to one relation between schedule and userHomeCourts
    return $this->belongsTo(UserHomeCourt::class, 'userHomeCourtId', 'userHomeCourtId');
  }
}

现在您已准备好构建查询。此查询与使用查询构建器构建的查询略有不同。此外,laravel eloquent查询的输出也不同。您必须在查看时调整该结果:

您可以这样查询:

$users = User::with('homeCourt', 'userHomeCourts.schedule')->where('timeTo', '>', ,$request->currentTime)->get();

此查询只是一个示例,您必须根据您的要求进行定义。这里,with方法的参数是与其他表的users表关系的方法名称。这是它的工作原理。

您可以在此处阅读更多内容:https://laravel.com/docs/5.4/eloquent-relationships