Laravel - 如何 link 下拉列表中的数据 table 到另一个资源模型

Laravel - How to link data from drop down table into another resource model

我有一个 Profile.php 模型,其中 state_id 是从 states table 中保存的。我如何 link 状态 table 到 json.

中返回的配置文件实例

{ "profile_id" : 1, "state" : {state data} }

状态数据应包含为配置文件模型存储的 state_id 的特定状态模型。

分别考虑两个模型 - ProfileState,然后可以构建如下关系 -

配置文件模型内部 -

/**
 * 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();