【问题标题】:many-to one relationship Eloquoent Orm多对一关系 Eloquent Orm
【发布时间】: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');
    }
}

期待您的回复

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    尝试先修复你们的关系,然后再试一次。在 State 模型中这样定义

    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的国家。所以只需修复你的关系就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 2016-02-11
      • 2015-04-16
      • 2014-12-14
      • 2018-12-29
      • 2020-11-08
      • 1970-01-01
      相关资源
      最近更新 更多