Sunday, April 2, 2017

Laravel: Where selection for Eloquent Eager Loading relationship

I got two DB tables:

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

I use laravel as back-end. Now I want to implement filtering data for my front-end. So the user can select a country name and laravel should answer the request only with posts that have a country with the specified name.

How could I add this condition to my existing pagination query? I tried this:

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

... resulting 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)



via HelloWorld0815

Advertisement