Php 多对一关系口述Orm

Php 多对一关系口述Orm,php,laravel,Php,Laravel,我对能言善辩的ORM有一个挑战,因为拉威尔实际上是一个对能言善辩的ORM的新手。我有一个模范国家和一个模范州。状态表有一个外键countryId。问题是,如果我使用如下关系的急切加载获取所有状态 $countries = State::with('country')->get(); 我的状态模型如下 class State extends Model { protected $fillable = ['name', 'countryId']; protected $tab

我对能言善辩的ORM有一个挑战,因为拉威尔实际上是一个对能言善辩的ORM的新手。我有一个模范国家和一个模范州。状态表有一个外键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
}
]
我得到的结果如下

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输出可以看出,第二个item country对象没有加载。 我还试图在国家模式上建立关系,但没有改变

class Country extends Model
{
    protected $fillable = ['name'];
    protected $table = 'countries';
    function State(){
        return $this->hasMany('State', 'countryId');
    }
}

感谢期待您的回复

请先修复关系,然后再试一次。在状态模型中这样定义它

public function country(){ //lower 'c' NOT capital 
    return $this->belongsTo(Country::class, 'countryId'); //Pass the class AND the foreign key. You passed the primary key
}
然后再试一次

第二个没有国家/地区的原因是您在关系中设置了“id”,并且没有具有“id”2的国家/地区。所以,只要修复你们的关系,你们就应该很好地走了