繁体   English   中英

Laravel:雄辩渴望加载关系的选择

[英]Laravel: Where selection for Eloquent Eager Loading relationship

我有两个数据库表:

帖子

$table->increments('id');
$table->integer('country_id')->unsigned();
$table->foreign('country_id')->references('id')->on('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)

其中,方法根据Laravel代码库接受参数,

 /**
 * Add a relationship count / exists condition to the query with where clauses.
 *
 * @param  string  $relation
 * @param  \Closure|null  $callback
 * @param  string  $operator
 * @param  int     $count
 * @return \Illuminate\Database\Eloquent\Builder|static
 */
public function whereHas($relation, Closure $callback = null, $operator = '>=', $count = 1)
{
    return $this->has($relation, $operator, $count, 'and', $callback);
}

所以稍微修改一下代码,

$query = ""    

if ($request->has('country'){
$query = Post::with("country")->whereHas("country",function($q) use($request){
    $q->where("name","=",$request->country);
})->get()
}else{
    $query = Post::with("country")->get();
}

顺便说一下,上面的代码可以简化如下:

$query = ""    

if ($request->has('country'){
  $query = Post::with(["country" => function($q) use($request){
  $q->where("name","=",$request->country);
}])->first()
}else{
  $query = Post::with("country")->get();

}

$query = ""    

if ($request->has('country'){
    $query = Post::with("country")->whereHas("country", function($q) use($request){
        $q->where("name","=",$request->country);
   })->get()
}else{
    $query = Post::with("country")->get();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM