首页 > 解决方案 > 带有“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 查询有什么问题?

谢谢!

标签: laravelrelationship

解决方案


您需要调用matchesSetas 函数来触发查询并用于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


推荐阅读