Laravel 根据来自不同 table 的外键进行搜索
Laravel search based on foreign key from a different table
我有三个表 post,用户和国家。
Post 由来自某个国家/地区的用户保存。
现在我想搜索一个国家/地区所有用户的所有 post。
所以用户将按国家/地区过滤,我从搜索框获取国家/地区代码到控制器 $request->input($country);
这是我的模型关系:
POST 型号:
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...
);
}
}
我有三个表 post,用户和国家。 Post 由来自某个国家/地区的用户保存。 现在我想搜索一个国家/地区所有用户的所有 post。
所以用户将按国家/地区过滤,我从搜索框获取国家/地区代码到控制器 $request->input($country);
这是我的模型关系:
POST 型号:
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...
);
}
}