【问题标题】:Laravel Search BelongsToLaravel 搜索属于
【发布时间】:2020-11-08 12:31:18
【问题描述】:

我正在制作一个搜索功能,并且我正在使用 orWhere,但是,我遇到了一个问题,我想通过文本搜索 brand_id。在我的模态中,我将其设置为 belongsTo 但有什么方法可以让我在 MySQL 搜索词中使用它?

我的搜索查询

$products = Product::where('name', 'LIKE', '%' . $searchTerm . '%')
->orWhere('title', 'LIKE', '%' . $searchTerm . '%')
->orWhere('description', 'LIKE', '%' . $searchTerm . '%')
->orWhere('allergies', 'LIKE', '%' . $searchTerm . '%')
->orWhere('price', 'LIKE', '%' . $searchTerm . '%')->paginate(15);

我想以某种方式包含品牌名称,而不是数据库中的brand_id。有没有办法做到这一点?我在我的产品模型中像这样链接了它

public function brand()
{
    return $this->belongsTo(Brand::class);
}

【问题讨论】:

  • Welcome to SO ...您可以使用查询关系(特别是关系存在)的方法通过具有特定值的关系的存在来过滤结果集

标签: php laravel


【解决方案1】:

你可以使用 orWhereHas:

$products = Product::where('name', 'LIKE', '%' . $searchTerm . '%')
                ->orWhere('title', 'LIKE', '%' . $searchTerm . '%')
                ->orWhere('description', 'LIKE', '%' . $searchTerm . '%')
                ->orWhere('allergies', 'LIKE', '%' . $searchTerm . '%')
                ->orWhere('price', 'LIKE', '%' . $searchTerm . '%')
                ->orWhereHas('brand', function($q) use ($searchTerm){
                    $q->where('name', 'LIKE', "%{$searchTerm}%");
                })
                ->paginate(15);

https://laravel.com/docs/master/eloquent-relationships#querying-relationship-existence

【讨论】:

  • 谢谢!这正是我要找的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
  • 2019-03-08
  • 2018-03-23
  • 2018-08-06
  • 1970-01-01
  • 1970-01-01
  • 2021-01-19
相关资源
最近更新 更多