必须是App,Relationship,Illuminate BelongsToMany的实例返回

时间:2019-05-25 19:27:53

标签: laravel laravel-5 relationship

当尝试在Laravel中通过属人对多关系附加程序时,出现一个错误。有人知道我在做什么错吗?

控制器

$user = User::where('id', $request->input('user_id'))->first();
$program = Program::where('id', $request->input('program_id'))->first();
$update = $user->programs()->attach($program);

关系

public function programs() : Relation
{
    return $this->belongsToMany(\App\Program::class, 'program_user');
}

我遇到了此错误->“ App \ User :: programs()的返回值必须是App \ Relation的实例,Illuminate \ Database \ Eloquent \ Relations \ BelongsToMany的实例返回”

1 个答案:

答案 0 :(得分:1)

尝试从: Relation方法中将BelongsToMany删除或更改为programs()。俗话说,该函数返回Relation,但它返回的是BelongsToMany关系。