im试图制作一个返回等于搜索结果的记录的搜索字段。我有2种型号,品牌和汽车。我的关系是品牌(欧宝,铃木等)有许多汽车,一辆汽车属于品牌。
品牌模型
class Brand extends Model
{
protected $fillable = [
'brandname'
];
public function cars(){
return $this->hasMany(Car::class);
}
}
汽车模型
class Car extends Model
{
public function brand(){
return $this->belongsTo(Brand::class);
}
protected $fillable = [
'user_id', 'brand_id', 'year', 'licensplate'
];
}
我有一个页面,显示所有汽车都有一些信息。查找汽车形式
这是页面的DE代码:
<div class="col-sm-8 blog-main">
<h1>Alle auto's</h1><hr>
<form method="POST" action="/allcars">
{{csrf_field()}}
<div class="form-group">
<input type="text" name="searchfield" placeholder="Merk">
<button type="submit">Zoek</button>
</div>
</form>
@foreach($brands as $brand)
@foreach($brand->cars as $car)
<div class="form-group">
<h5>
{{$brand->brandname}}
</h5>
Kenteken: {{$car->licensplate}}<br>
Bouwjaar: {{$car->year}}<br>
</div>
@endforeach
@endforeach
</div>
这是我的路由文件:
路由
Route::post('/allcars', 'CarController@show');
最后我的控制器文件: Carcontroller.php
public function show(){
$input = request('searchfield');
if(empty($input))
{
return back();
}
else if(is_numeric($input))
{
// Search on year
$brands = Brand::with('cars')->whereHas('cars', function($q)
{
$input = request('searchfield');
$q->where('year', $input);
})->get();
return view('content.cars.index', compact('brands'));
}
else
{
// Search on brandname
$brands = Brand::with('cars')->get()->where('brandname', $input);
return view('content.cars.index', compact('brands'));
}
}
其他如果语句正常工作。当整数(年)被填写时,它会使用"年度搜索",当填充字符串时,请使用品牌搜索。
但是,品牌搜索正常工作。如果我在"欧宝"上搜索,我将获得所有汽车,并提供一些来自欧宝品牌的信息。但是,当我在1990年搜索时,我会得到一个拥有1990年汽车的品牌,然后我也从该品牌那里获得了其他汽车。
示例:
如果我搜索1990,我会得到3辆汽车:欧宝(1990),欧佩尔(2000)和欧佩尔(1882)。
另一个示例:我在2000年搜索,我得到5辆车:欧宝(2000),欧宝(1990),欧宝(1882),宝马(2000),宝马(1721)。
我认为我在代码中做错了什么,请纠正我。这些是我的迁移:汽车迁移
Schema::create('cars', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedInteger('brand_id');
$table->foreign('brand_id')->references('id')->on('brands')->onDelete('cascade');
$table->string('year');
$table->string('licensplate');
$table->timestamps();
});
品牌迁移
Schema::create('brands', function (Blueprint $table) {
$table->increments('id');
$table->string('brandname');
$table->timestamps();
});
如果要更改其他内容:
else if(is_numeric($input))
{
// Search on year
$brands = Brand::with(['cars' => function ($q) use ($input) {
$q->where('year',$input);
}])->get();
return view('content.cars.index', compact('brands'));
}