[英]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調用未定義的方法Modules \\ Survey \\ Repositories \\ Eloquent \\ EloquentQuestionsRepository :: surveys()
我注意到該錯誤提到了EloquentQuestionsRepository
但是我沒有在其中添加任何方法,因此它只是一個空類:
class EloquentQuestionsRepository extends EloquentBaseRepository implements QuestionsRepository
{
}
QuestionRepository:
interface QuestionsRepository extends BaseRepository
{
}
如對主要帖子的答復所述,構造函數將QuestionsRepository
解析為EloquentQuestionsRepository
實例,從外觀上看,這並不是store
方法所需要的。
我可能要做的就是直接在模型上調用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.