Reputation: 57
That's my table:
countries
id - integer
name - string
users
id - integer
country_id - integer
name - string
posts
id - integer
user_id - integer
title - string
In my case I just want to list the posts in the country where like '%keyword%'. I have defined on the country model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
/**
* Get all of the posts for the country.
*/
public function posts()
{
return $this->hasManyThrough('App\Post', 'App\User');
}
}?>
Now,the user will input a country name or a post title keyword to search the posts.My controller:
public function posts()
{
$param = Input::all();
if (isset($param['country']) && $param['country']) {
$query = Posts::whereHas('country', function($q) use ($param) {
$q->where('name', 'like', '%' . $param['country'] . '%');
});
}
}
How to define country relation in posts model?belongToThrough has tried but not work.Many tks!
Upvotes: 3
Views: 292
Reputation: 3681
The problem that you're facing is that there is no reverse of the "hasManyThrough" relationship, i.e. there is no such thing as "belongsToThrough".
You will probably have do to this with an explicit join, e.g.
$query = Post::where('countries.name', 'like', '%' . $param['country'] .'%')
->join('users', 'users.id', '=', 'posts.user_id')
->join('countries', 'countries.id', '=', 'users.country_id')
Upvotes: 1