2017-07-08 98 views
0

我已經成功創建了「預訂」表中的自動完成搜索框,但是我希望自動完成搜索框顯示來自表'病人根據使用特定的條件‘其中’條件,如何根據「where」條件使用外鍵從另一個表中創建自動完成的顯示數據

這是預訂控制器,我在它添加自動完成:

namespace App\Http\Controllers; 

use Illuminate\Http\Request; 
use App\Booking; 
use App\Patient; 
use App\User; 
use Session; 
use DB; 
use Auth; 
use Input; 
class BookingController extends Controller 
{ 
    public function __construct() 
    { 
     $this->middleware('auth'); 
    } 
    /** 
    * Display a listing of the resource. 
    * 
    * @return \Illuminate\Http\Response 
    */ 
    public function index() 
    { 

$search = \Request::get('search'); 

$bookings = Booking::whereHas('patient', function ($query) use ($search) { 
    $query->where('patient_name', 'like', '%' . $search . '%'); 
})->where('status','=', null)->whereHas('patient', function ($query){ 
    $query->where('company_id','=' ,Auth::user()->company_id); 
})->paginate(10); 




     return view('booking.index')->withBookings($bookings); 
    /** 
    * Show the form for creating a new resource. 
    * 
    * @return \Illuminate\Http\Response 
    */ 


public function autoComplete(Request $request) { 
     $query = $request->get('term',''); 

     $bookings=Booking::whereHas('patient', function ($query){ 
     $query->where('company_id','=' ,Auth::user()->company_id); 

     })->$data=array(); 
     foreach ($bookings as $booking) { 
       $data[]=array('value'=>$booking->patient->patient_name,'id'=>$booking->id); 
     } 
     if(count($data)) 
      return $data; 
     else 
      return ['value'=>'No Result Found','id'=>'']; 
    } 

,這是預訂型號:

class Booking extends Eloquent 
{ 

public function patient() 
    { 
    return $this->belongsTo('App\Patient'); 

    } 

    public function user() 
    { 
    return $this->belongsTo('App\User'); 

    } 
} 

,這是患者型號:

class Patient extends Eloquent 
{ 
    public function booking() 
    { 
    return $this->hasMany('App\Booking'); 

    } 

    public function user() 
    { 
    return $this->belongsTo('App\User'); 

    } 
} 

和我用這個代碼在視圖:

{!! Form::text('search_text', null, array('placeholder' => 'Search Text','class' => 'form-control','id'=>'search_text')) !!} 

我想顯示從「患者」表中的數據,有一個一個之間一對多關係「預訂」和「病人」表,我已經成功地做了一個搜索框在患者表中搜索,你可以在索引功能中看到,但我不知道顯示來自「患者」表的數據,使用條件來顯示patient_name,他的company_id相等認證用戶company_id

抱歉,我的語言差。

回答

0

你應該能夠加載使用withpatient關係:

$bookings = Booking::with('patient') 
    ->whereHas('patient', function ($query) use ($search) { 
     $query->where('company_id', Auth::user()->company_id) 
      ->where('patient_name', 'like', '%' . $search . '%'); 
    }) 
    ->whereNull('status') 
    ->paginate(10); 

https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

此外,您只需要使用->whereHas('patient'...一次。

希望這會有所幫助!

+0

我需要編輯自動完成以顯示來自「患者」表的數據,而不是搜索功能 –

相關問題