Laravel: Where is the Choice for Eloquent Eager Loading Relations

I have two DB tables:

Posts

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

      

Country

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

      

I am using laravel as back-end. Now I want to implement filtering data for my interface. This way the user can select the country name and laravel has to respond to the request with only posts that have a country with the given name.

How can I add this condition to an existing pagination query? I've tried this:

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

      

... results in the following error:

Column not found: 1054 Unknown column 'country.name' in 'where clause' (SQL: select count(*) as aggregate from `posts` where `country`.`name` = Albania)

      

+3


source to share


2 answers


whereHas method takes a parameter according to Laravel code base,

 /**
 * 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);
}

      

so by changing the code a little,

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

      



By the way, the above code can be simplified a bit as follows:

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

      

}

+5


source


$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


source







All Articles