[英]Search function with one to one relationship in Laravel 5.4
I would like to make a simple search function for my table. 我想为我的桌子做一个简单的搜索功能。 This table get the data from two mssql [Addresses] and [Companies] tables.
该表从两个mssql [Addresses]和[Companies]表中获取数据。 The tables have one to one relationship.
这些表具有一对一的关系。
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');
}
The relationship is one address one company. 关系是一家公司的一个地址。 The first table adress have name, street, city columns and the second table have compName, compType.
第一个表地址具有名称,街道,城市列,第二个表具有compName,compType。
class Company extends Model
{
protected $table = "Company";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function addresses()
{
return $this->belongsTo(Addresses::class, 'adress');
}
}
this are the two models. 这是两个模型。 The controller look like this:
控制器如下所示:
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'));
}
}
i can search after the first table columns (city, name, street). 我可以在第一个表格列(城市,名称,街道)之后搜索。 but how can i search after the second table columns like the compName.
但是我该如何搜索像compName这样的第二个表列。
Just add orWhere
for every company table field you want to search on in whereHas
closure. 只需添加
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.