为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel 搜索属于

Laravel 搜索属于

PHP
婷婷同学_ 2023-08-11 17:52:44
我正在制作一个搜索功能,并且正在使用 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);我想以某种方式包含品牌名称,而不是数据库中的品牌 ID。有什么办法可以做到这一点吗?我在我的产品模型中将其像这样链接起来public function brand(){    return $this->belongsTo(Brand::class);}
查看完整描述

1 回答

?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

您可以使用 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);
查看完整回答
反对 回复 2023-08-11
  • 1 回答
  • 0 关注
  • 117 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号