【问题标题】:Amending foreign key on a Laravel relationship在 Laravel 关系上修改外键
【发布时间】:2019-04-11 04:52:12
【问题描述】:

在 Laravel (v5.7.12) 中,我有两个模型 - UserProject

一个用户有一个id,可以有很多项目。一个项目有一个owner_id

我似乎无法正确配置关系。在我的用户模型中,我有:

/**
 * Get the projects associated with the user.
 */
public function projects()
{
    $this->hasMany('\App\Project', 'owner_id', 'id');
}

在我的项目模型中,我有:

/**
 * Get the owner associated with the user.
 */
public function owner()
{
    $this->belongsTo('\App\User', 'id', 'owner_id');
}

但是调用$user->projects()$project->owner() 会返回null

我应该如何配置我的非标准关系键?

【问题讨论】:

    标签: laravel eloquent foreign-keys relationship


    【解决方案1】:

    你忘了返回方法:

    public function projects()
    {
        return $this->hasMany('\App\Project', 'owner_id');
    }
    

    对第二个也这样做:

    public function owner()
    {
        return $this->belongsTo('\App\User', 'owner_id');
    }
    

    【讨论】:

    • 啊啊啊啊啊啊。我必须成功地完成了几十次!感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2019-07-20
    • 2019-03-27
    • 2016-12-22
    • 1970-01-01
    • 2020-04-04
    • 2020-08-13
    相关资源
    最近更新 更多