duangou1868 2017-09-28 11:48
浏览 81
已采纳

Laravel attach为belongsToMany关系返回undefined方法

I would like to create a question which has many surveys. In the questions Model:

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

And in the controller when saving a new question:

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')]));
}

But I get the following error when it gets to the attach line:

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

I notice the error mentions EloquentQuestionsRepository but I have added no methods in there so it's just an empty class:

class EloquentQuestionsRepository extends EloquentBaseRepository implements QuestionsRepository
{
}

QuestionRepository:

interface QuestionsRepository extends BaseRepository
{
}
  • 写回答

1条回答 默认 最新

  • dougan5772 2017-09-28 13:10
    关注

    As explained in the response to the main post - the constructor resolves the QuestionsRepository to instance of EloquentQuestionsRepository, which by the look of it is not what the store method needs.

    What I would probably do is to make call to create method directly on the model and remove constructor all together - that is unless you need the instance of QuestionsRepository anywhere else in your controller:

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

    Also - I'm not sure passing $request->all() is the best thing to do - I'd probably use $request->only(...) or $request->all(...) specifying which items you want to get from the request rather than passing everything from the request to the create method.

    On the other note - you could also use Form Request, which would validate data for your before passing it to the store method.

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程