我有三个表post、user和country。帖子由来自某个国家/地区的用户保存。现在我想搜索一个国家所有用户的所有帖子。
所以用户将按国家过滤,我从搜索框到控制器获取国家代码$请求-
以下是我的模型关系:
后模型:
class Post extends Model
{
protected $table = 'posts';
protected $dates = ['status_change'];
public function photos()
{
return $this->hasMany(Photo::class,'post');
}
public function make_rel()
{
return $this->belongsTo(Make::class, 'make_id' ,'id','make_logo');
}
public function user_rel()
{
return $this->belongsTo(User::class, 'created_by' ,'id');
}
}
国家模式:
class Country extends Model
{
public function users(){
return $this->hasMany('App\User');
}
}
用户模型:
class User extends Authenticatable
{
public function country_rel()
{
return $this->belongsTo(Country::class, 'country' ,'country_code');
}
}
搜索功能
public function search(Request $request)
{
$this->validate($request, [
'country' => 'required',
]);
$country = Country::where('country_name',$request->input('country'))->get();
$data = Post::where('created_by',$country->user_rel->name)
->get();
dd($data);
}
这不是工作。有人能告诉我我做错了什么吗?
我会用hasManyThrugh。文档甚至使用了您的确切用例:
class Country extends Model
{
public function users(){
return $this->hasMany('App\User');
}
public function posts() {
return $this->hasManyThrough(
'App\Post',
'App\User',
'country_id', // Foreign key on users table...
'user_id', // Foreign key on posts table...
'id', // Local key on countries table...
'id' // Local key on users table...
);
}
}