【发布时间】:2017-02-07 20:23:17
【问题描述】:
我在 larval 中使用 hasManythrough 关系时遇到问题。只需按照文档使用那里的示例,它们是:
countries
id - integer
name - string
users
id - integer
country_id - integer
name - string
posts
id - integer
user_id - integer
title - string
这是我在模型中设置关系的方式
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
public function posts() {
return $this->hasManyThrough('App\Post', 'App\User', 'user_id', 'country_id', 'id');
}
}
这是用户模型
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts() {
return $this->hasMany('App\Post');
}
public function country() {
return $this->hasOne('App\User');
}
}
这是帖子模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user() {
return $this->belongsTo('App\User');
}
}
因此,该网站没有详细说明如何通过国家模型提取帖子。使用路由文件,这是我使用的查询
Route::get('posts/countries/{id}', function($id) {
$countries = App\Country::where('id', $id)->get();
return $countries->posts;
});
在我看来,我按照文档所说的方式正确地建立了关系。 users 表上有一个 country_id,所以我不确定查询是否错误,或者我确实设置了不正确的关系。
【问题讨论】:
标签: laravel relationships