Laravel attach returns belongsToMany 关系的未定义方法

Laravel attach returns undefined method for belongsToMany relationship

我想创建一个有很多调查的问题。题型中:

public function surveys()
{
    return $this->belongsToMany(Survey::class, 'survey__surveyquestions');
}

并在保存新问题时在控制器中:

private $questions;

public function __construct(QuestionsRepository $questions)
{
    parent::__construct();

    $this->questions = $questions;
}

public function store(Request $request)
{
    $this->questions->create($request->all());

    $this->questions->surveys()->attach($request->surveys);

    return redirect()->route('admin.survey.questions.index')
        ->withSuccess(trans('core::core.messages.resource created', ['name' => trans('survey::questions.title.questions')]));
}

但是当它到达附加行时出现以下错误:

(1/1) FatalErrorException Call to undefined method Modules\Survey\Repositories\Eloquent\EloquentQuestionsRepository::surveys()

我注意到错误提到 EloquentQuestionsRepository 但我没有在其中添加任何方法所以它只是一个空的 class:

class EloquentQuestionsRepository extends EloquentBaseRepository implements QuestionsRepository
{
}

问题库:

interface QuestionsRepository extends BaseRepository
{
}

如对主要 post 的响应中所述 - 构造函数将 QuestionsRepository 解析为 EloquentQuestionsRepository 的实例,从外观上看这不是 [=13] =]方法需要。

我可能会做的是直接在模型上调用 create 方法并一起删除构造函数 - 也就是说,除非您在控制器中的其他任何地方都需要 QuestionsRepository 的实例:

public function store(Request $request)
{
    $question = Question::create($request->all());

    $question->surveys()->attach($request->surveys);

    ...

}

另外 - 我不确定传递 $request->all() 是最好的做法 - 我可能会使用 $request->only(...)$request->all(...) 指定你想从请求而不是将请求中的所有内容传递给 create 方法。

另一方面 - 您也可以使用 Form Request,它会在将数据传递给 store 方法之前验证您的数据。

https://laravel.com/docs/5.5/validation#form-request-validation