如何根据“where”条件使用外键从另一个表中创建自动完成的显示数据
问题描述:
我已经成功创建了“预订”表中的自动完成搜索框,但是我希望自动完成搜索框显示来自表'病人根据使用特定的条件‘其中’条件,如何根据“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
抱歉,我的语言差。
答
你应该能够加载使用with
的patient
关系:
$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'...
一次。
希望这会有所帮助!
我需要编辑自动完成以显示来自“患者”表的数据,而不是搜索功能 –