2017-04-02 50 views
2

我有兩個數據庫表:Laravel:如果選擇了雄辯的預先加載關係

帖子

$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) 

回答

4

whereHas方法接受參數按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(); 

}

0
$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(); 
} 
+0

給我:'FatalErrorException在PostController.php線77: 語法錯誤,意想不到 '=>'(T_DOUBLE_ARROW)'錯誤。 – HelloWorld0815

+0

我已更新它。我犯了一個錯誤把箭頭放在那裏 – oseintow