我想为我的桌子做一个简单的搜索功能。该表从两个mssql [Addresses]和[Companies]表中获取数据。表格具有一对一的关系。
class Addresses extends Model
{
protected $table = "Addresses";
protected $primaryKey = 'adress';
public $timestamps = false;
public function scopeSearchAddress($query, $searchTerm)
{
return $query->where('city', 'LIKE', '%'.$searchTerm.'%')
->orWhere('name', 'LIKE', '%'.$searchTerm.'%')
->orWhere('street', 'LIKE', '%'.$searchTerm.'%');
}
public function company()
{
return $this->hasOne(Company::class, 'adress');
}
这种关系是一个公司的地址。 第一个表格地址有名称,街道,城市列,第二个表格有compName,compType。
class Company extends Model
{
protected $table = "Company";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function addresses()
{
return $this->belongsTo(Addresses::class, 'adress');
}
}
这是两个型号。控制器看起来像这样:
class AddressesController extends Controller
{
public function index(Request $request)
{
$searchTerm = $request->input('searchTerm');
$addresses = Addresses::whereHas('compan', function($query) {
$query->where('compType','D');
})->orderBy('Name')
->searchAddress($searchTerm)
->paginate(60);
return view('asdress.index', compact('addresses', 'searchTerm'));
}
}
我可以搜索第一个表格列(城市,名称,街道)。但是如何在第二个表格列之后搜索,比如compName。
答案 0 :(得分:1)
只需在orWhere
关闭中为要搜索的每个公司表字段添加whereHas
。
$searchTerm = $request->input('searchTerm');
$addresses = Addresses::whereHas('company', function($query) use($searchTerm){
$query->where('compType','D')
//append other where queries on company fields
->orWhere('company_table_field_name', $searchTerm);
});