gpt4 book ai didi

php - Laravel 搜索关系

转载 作者:IT王子 更新时间:2023-10-28 23:52:37 26 4
gpt4 key购买 nike

我有两个相关的模型。我正在尝试在产品中进行搜索,并且只显示实际的搜索结果,而不是找到该产品的类别的所有产品。我不想搜索任何类别,因为无论搜索什么或找到什么,类别都会始终显示。

Example. I have the following categories:

- Food
- Drinks
- Candy

My "Food" category has the following products:

- Strawberry
- Apple
- Banana

My "Drinks" category has the following products:

- Banana Cocktail
- Beer
- Cola

My "Candy" category has the following products:

- Strawberry Lollipop
- Chocolate Bar
- Banana Ice Cream

所以,我想要实现的是以下内容。我搜索了一种名为“香​​蕉”的产品。我想要显示的是:

Category Food
- Product Banana

Category Drinks
- Product Banana Cocktail

Category Candy
- Product Banana Ice Cream

但我的问题是,对于我的代码,如果我执行“香蕉”搜索,它会显示找到香蕉的类别,然后返回并显示该类别中的所有产品,而不是仅显示我搜索的产品为了。我怎样才能做到只显示搜索到的产品?

类别模型:

class Categories extends Eloquent {

public function products()
{
return $this->hasMany('Products');
}
}

产品型号:

class Products extends Eloquent {

public function categories()
{
return $this->belongsTo('Categories');
}
}

我的 Controller :

    $searchString       = Input::get('search');

if($searchString)
{
$categories = Categories::with('products')->orderBy($order, $by)->whereHas('products', function ($query) use ($searchString){
$query->where('name', 'like', '%'.$searchString.'%');
})->get();
}
else {
$categories = Categories::with('products')->orderBy($order, $by)->get();
}

我的看法:

@foreach($categories as $category)
{{ $category->name }} // Show the category name

@foreach($category->products as $product)
{{ $product->name }} // Show all products in that category

@endforeach
@endforeach

最佳答案

我不知道您如何看待结果,但我认为如果您只是急于将产品加载到类别中,那应该不错。

$categories = Categories::whereHas('products', function ($query) use ($searchString){
$query->where('name', 'like', '%'.$searchString.'%');
})
->with(['products' => function($query) use ($searchString){
$query->where('name', 'like', '%'.$searchString.'%');
}])->get();

foreach($categories as $category){
echo $category->name . ':' . PHP_EOL;
foreach($category->products as $product){
echo . '-' . $product->name . PHP_EOL;
}
}

关于php - Laravel 搜索关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31871962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com