我已在“预订”表中成功创建了一个自动完成搜索框,但我希望自动完成搜索框根据使用“where”条件的特定条件显示“患者”表中的数据,
这是我在其中添加自动完成功能的预订 Controller :
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');
}
}
我在 View 中使用了这段代码:
{!! Form::text('search_text', null, array('placeholder' => 'Search Text','class' => 'form-control','id'=>'search_text')) !!}
我想显示“病人”表中的数据,“预订”和“病人”表之间存在一对多关系,我已经成功创建了一个搜索框来在病人表中搜索,正如您在索引函数中看到的那样,但我不知道使用 where 条件显示“病人”表中的数据来显示他的 company_id
等于经过身份验证的用户 company_id
抱歉我的语言不好。
最佳答案
您应该能够使用 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('patent'...
一次。
希望这有帮助!
关于php - 如何根据 "where"条件使用外键自动完成显示另一个表中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44990277/