我已成功在“预订”表中创建了一个自动完成搜索框,但我希望自动完成搜索框根据特定条件使用“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')) !!}
我想显示来自“患者”表的数据,并且“预约”和“患者”表之间存在一对多的关系,我已经成功地在搜索框中搜索患者表,您可以在索引功能中看到,但我不知道显示“患者”表中的数据使用where条件显示patient_name
他的company_id
等于经过身份验证的用户company_id
对不起我的坏语言。
答案 0 :(得分:0)
您应该可以使用patient
加载with
关系:
$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'...
一次。
希望这有帮助!