修改拉拉威尔关系的外国密钥



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

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

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

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

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

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

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

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

您忘记返回方法:

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

对第二个也这样做:

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

最新更新