Laravel:选择Eloquent Eager Loading的关系

时间:2017-04-02 22:24:38

标签: php laravel laravel-5 eloquent eager-loading

我有两个数据库表:

帖子

from pynput import mouse

class MyException(Exception):pass

NumberOfMouseClicks = 0

def on_click(x, y, button, pressed):
    global NumberOfMouseClicks
    print(x, y)
    NumberOfMouseClicks = NumberOfMouseClicks + 1
    if (NumberOfMouseClicks==10):
        raise MyException(button)

with mouse.Listener(on_click=on_click) as listener:
    try:
        listener.join()
    except MyException as e:
        pass

国家/地区

$table->increments('id');
$table->integer('country_id')->unsigned();
$table->foreign('country_id')->references('id')->on('countries');

我使用laravel作为后端。现在我想为我的前端实现过滤数据。因此,用户可以选择国家/地区名称,而laravel应仅使用具有指定名称的国家/地区的帖子来回答请求。

如何将此条件添加到我现有的分页查询中?我试过这个:

$table->increments('id');
$table->string('name', 70);

...导致以下错误:

$query = app(Post::class)->with('country')->newQuery(); 
// ...
if ($request->exists('country')) {
        $query->where('country.name', $request->country);
}
// ...

2 个答案:

答案 0 :(得分:13)

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();

}

答案 1 :(得分: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();
}