【发布时间】:2017-03-09 14:31:27
【问题描述】:
我对 Eloquent ORM 有一个挑战,因为 laravel 实际上我是这个 Eloquoent orm 的新手。我有一个模范国家和一个模范州。 state 表有一个 foreign_key countryId。问题是如果我使用预先加载的关系获取所有状态,如下所示。
$countries = State::with('country')->get();
我的状态模型如下
class State extends Model
{
protected $fillable = ['name', 'countryId'];
protected $table = 'states';
function Country(){
return $this->belongsTo('Country','id');
}
}
我得到的结果如下
[
{
"id": 1,
"name": "Lagos",
"countryId": "1",
"created_at": "2017-03-09 13:09:12.000",
"updated_at": "2017-03-09 13:09:12.000",
"country":{"id": 1, "name": "Nigeria", "created_at": "2017-03-09 10:55:46.000", "updated_at": "2017-03-09 10:55:46.000"…}
},
{
"id": 2,
"name": "Oyo",
"countryId": "1",
"created_at": "2017-03-09 13:29:12.000",
"updated_at": "2017-03-09 13:29:12.000",
"country": null
}
]
从json输出中可以看出,第二项country对象没有加载。 我也尝试在 Country 模型上建立关系,但没有任何变化
class Country extends Model
{
protected $fillable = ['name'];
protected $table = 'countries';
function State(){
return $this->hasMany('State', 'countryId');
}
}
期待您的回复
【问题讨论】: