Laravel使用外键自动完成显示来自另一个表的数据

时间:2017-07-10 18:23:40

标签: mysql ajax laravel autocomplete

我已在“预订”控制器中创建了一个自动完成搜索框。表格成功,但我希望自动完成搜索框显示来自另一个表格“患者”的数据。与"预订"有一对多的关系表根据具体情况使用'其中'条件,

这是我在其中添加自动填充的预订控制器:

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

    }
}
and this is the patient Model:

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

我想显示来自"患者"的数据表和"预订"之间存在一对多的关系。和"患者"表,我已经成功地在患者表中搜索了一个搜索框,你可以在索引函数中看到,但我不知道显示来自"患者" table使用where where来显示patient_name,他的company_id等于Authenticated user company_id

抱歉我的坏语。

0 个答案:

没有答案