【发布时间】:2021-09-02 20:34:43
【问题描述】:
我有一个Profile.php 模型,其中state_id 是从states 表中保存的。如何将状态表链接到 json 中返回的配置文件实例。
{ "profile_id" : 1, "state" : {state data} }
状态数据应包含为配置文件模型存储的state_id 的特定状态模型。
【问题讨论】:
标签: php json laravel eloquent model
我有一个Profile.php 模型,其中state_id 是从states 表中保存的。如何将状态表链接到 json 中返回的配置文件实例。
{ "profile_id" : 1, "state" : {state data} }
状态数据应包含为配置文件模型存储的state_id 的特定状态模型。
【问题讨论】:
标签: php json laravel eloquent model
分别考虑两个模型 - Profile 和 State,然后可以构建如下关系 -
Profile 模型内部 -
/**
* Get associated state for the profile.
*
* @return \Illuminate\Database\Eloquent\Relations\belongsTo
*/
public function state()
{
return $this->belongsTo(State::class);
}
内部状态模型 -
/**
* Get associated profiles for the state.
*
* @return \Illuminate\Database\Eloquent\Relations\hasMany
*/
public function profile()
{
return $this->hasMany(Profile::class);
}
查询:
$profileWithState = Profile::with('state')->get();
【讨论】: