Laravel从数据库搜索到许多关系

问题描述 投票:0回答:1

我在多对多关系模型中都有搜索问题。让我解释 :我有在线教育网站。这包括预订,老师,学生。学生和老师是用户的角色。我想通过在搜索输入中使用名称或电子邮件从数据库中搜索过去的预订,然后呈现到管理页面。让代码

admin/searchpastreservation.blade.php
    <div class="form-group col-md-6">                                
      <input class="form-control pb-2" id="search" name="search" type="search" 
        placeholder="@lang('admin.search')">
     </div>
     <div class="form-group col-md-3">
         <button type="submit" class="btn btn-primary mb-2 form-control">Search</button>
      </div>

pastReservationController.php
public function searchpastreservation(Request $request)
 {
    $search = $request->input('search');
    $now = Carbon::now(0);
    $reservations = Reservation::where('start','<',$now)->get();
    //Reservations table columns i need reservation_start and reservation_lenght
    $students=User::whereRoleIs('student')->get();
    $teacher = User:whereRoleIs('teacher')->get()
//and i really dont know how can i write query here.if there was only one tale, it is very simple. But there where lots of table. users,role(for teacher and student),role_user(pivot table) and for reservation reservations,reservations_user(pivot table) 
}

就这样。我不是主人,我只是个贪婪的人。我希望我能解释我的问题,希望有人能帮助我。

database laravel search many-to-many relationship
1个回答
0
投票

我认为您应该使用连接链到达所需的位置,

$result= Reservation::join('reservations_user','reservations.id','reservations_user.reservation_id')
->join('users','users.id','reservations_user.user_id')
->leftJoin('role_user','role_user.user_id','users.id')
->leftJoin('roles','role_user.role_id','roles.id')
->whereDate('reservations.start','<',Carbon::now())
->where(function($query)use($search)
{
$query->where('users.email',$search)
->orWhere('users.name','like', '%' .$search . '%');
})
->select('reservations.*','users.name','users.email','roles.name', ....)->get();
© www.soinside.com 2019 - 2024. All rights reserved.