Laravel eloquent 预加载限制错误

Laravel eloquent eager loading limit error

我有自定义查询,尝试获取 5 个限制的专业用户

代码

$professions = Profession::whereHas("users", function($q) use($query) {
    $q->where("professions.name", "like", "%$query%");
})->withCount('users')->with('users', function($q) {
    $q->take(5);
})->paginate(10);

然后收到错误消息:

ErrorException: mb_strpos() expects parameter 1 to be string, object given

为什么我会收到此错误以及如何修复此错误?

我从 github 那里读到这个 ​​issue comment 并尝试过,但出现这个错误

你在这一行犯了一个错误:

 $q->where("professions.name", "like", "%".$query."%");

您需要连接变量。 您收到此错误是因为 with() 采用关联数组来限制急切加载。尝试:

$professions = Profession::whereHas("users", function($q) use($query) {
    $q->where("professions.name", "like", "%".$query."%");
})->withCount('users')->with(['users' => function($q) {
    $q->take(5);
}])->paginate(10);