我有两个数据库表:
Posts
$table->increments('id');
$table->integer('country_id')->unsigned();
$table->foreign('country_id')->references('id')->on('countries');
Countries
$table->increments('id');
$table->string('name', 70);
我使用laravel作为后端 . 现在我想为我的前端实现过滤数据 . 因此,用户可以选择国家/地区名称,而laravel应仅使用具有指定名称的国家/地区的帖子来回答请求 .
如何将此条件添加到我现有的分页查询中?我试过这个:
$query = app(Post::class)->with('country')->newQuery();
// ...
if ($request->exists('country')) {
$query->where('country.name', $request->country);
}
// ...
...导致以下错误:
Column not found: 1054 Unknown column 'country.name' in 'where clause' (SQL: select count(*) as aggregate from `posts` where `country`.`name` = Albania)
2 回答
whereHas方法根据Laravel代码库接受参数,
所以改变代码一点,
顺便说一句,上面的代码可以稍微简化如下;
}