【问题标题】:Laravel - How to link data from drop down table into another resource modelLaravel - 如何将下拉表中的数据链接到另一个资源模型
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答,with 方法效果很好。
    猜你喜欢
    • 2016-02-24
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-15
    • 2019-10-02
    • 1970-01-01
    • 2014-06-22
    相关资源
    最近更新 更多