laravel - 带有“LIKE”问题的 Laravel 关系查询
问题描述
我在用户模型上有以下 LARAVEL 自我关系:
public function matchesSet(){
return $this->belongsToMany(self::class, 'matches', 'user_id', 'match_id')->withPivot('confirmed');
}
然后我运行:
User::first()->matchesSet->where('pivot.confirmed', true)->where('name','LIKE', 'John')->count()
或者
User::first()->matchesSet->where('pivot.confirmed', true)->where('name','John')->count()
我得到了预期的结果:在这种情况下为“1”。
但是如果我在 LIKE 查询中添加 % ,在任何这些变体中:
User::first()->matchesSet->where('pivot.confirmed', true)->where('name','LIKE', '%John%')->count()
User::first()->matchesSet->where('pivot.confirmed', true)->where('name','LIKE', '%{John}%')->count()
User::first()->matchesSet->where('pivot.confirmed', true)->where('name','LIKE', "%John%")->count()
User::first()->matchesSet->where('pivot.confirmed', true)->where('name','LIKE', "%{John}%")->count()
然后我得到错误的结果,在所有情况下:“0”。
我的 LIKE 查询有什么问题?
谢谢!
解决方案
您需要调用matchesSet
as 函数来触发查询并用于wherePivot
查询数据透视属性:
User::first()->matchesSet()->wherePivot('confirmed', true)->where('name', 'like', '%John%')->count();
否则,您只是指的是 的where
功能Illuminate\Database\Eloquent\Collection
。
有关更多信息,请查看通过中间表列过滤关系:https ://laravel.com/docs/7.x/eloquent-relationships#many-to-many
推荐阅读
- python - 在 groupby 和 reindex 之后前向填充特定列
- python - Python - 在 SQL 数据库中存储加密密钥
- c# - Xamarin.Android .Jar Binding --> 在哪里可以找到 MainActivity.cs 文件的 using 指令?
- javascript - 我们可以在父级中捕获错误但在子级中实现回退 - React Error Boundary
- spring-boot - Web3j:获取使用交易哈希传输的交易令牌的价值
- html - 为什么 col-md-3 将图像堆叠成一列
- javascript - 设置新的 chrome 创建选项卡的 localStorage
- shell - 鱼壳上的部分值为空时无法设置壳环境
- javascript - iframe 中的一些函数没有被执行
- python - 使用列表中的值查找字典键