【问题标题】:BadMethodCallException Laravel坏方法调用异常 Laravel
【发布时间】:2017-08-24 07:17:43
【问题描述】:

我有 3 个表,分别是 polls、poll_questions 和 poll_choices。它们的关系是 polls 有很多 poll_questions 和 poll_questions 有很多 poll_choices。我正在尝试插入,但我收到 poll_choices() 的错误 BadMethodCallException。

投票模型:

public function poll_questions() {
    return $this->hasMany(PollQuestion::class);
}

投票问题模型:

public function polls() {
    return $this->belongsTo(Poll::class, 'poll_id');
}

public function poll_choices() {
    return $this->hasMany(PollChoice::class);
}

投票选择模型:

public function poll_questions() {
    return $this->belongsTo(PollQuestion::class, 'poll_question_id');
}

这是我的控制器:

public function store(Request $request) {
    $rules = [
        'title'     => 'required',
        'questions' => 'required|poll_questions',
    ];

    $this->validate($request, $rules);


    $newPoll = Poll::create(request()->all());
    $questions = $request->input('questions');
    for ($i = 0; $i < count($questions); $i++) {
        $poll_question = new PollQuestion();
        $poll_question->input_type = $questions[$i]["input_type"];
        $poll_question->question = $questions[$i]["question"];

        $newPoll->poll_questions()->save($poll_question);

        if ($questions[$i]["input_type"] === '0') {
            for ($j = 0; $j < count($questions[$i]["choices"]); $j++) {
                $poll_choices = new PollChoice();
                $poll_choices->choice = $questions[$i]["choices"][$j];
                $newPoll->poll_questions()->poll_choices()->save($poll_choices);
            }
        }
    }

    return $this->showOne($newPoll);
}

我在这一行得到一个错误:$newPoll-&gt;poll_questions()-&gt;poll_choices()-&gt;save($poll_choices);

另外,我试过了:$newPoll-&gt;poll_questions-&gt;poll_choices()-&gt;save($poll_choices);

我可以完美地添加 poll 和 poll_question。但是当我尝试添加投票选项时,它给出了一个错误。我无法访问 poll_questions 的 poll_choices 方法。

我该如何解决这个问题?

Laravel 5.4

完整的错误日志:

BadMethodCallException 调用未定义的方法 Illuminate\Database\Query\Builder::poll_choices()

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    当您执行此操作时,您已经保存了投票问题并将其与投票相关联:

    $newPoll->poll_questions()->save($poll_question);
    

    所以剩下的就是保存问题的选择,您不再需要参与父投票。所以在你的问题循环中,使用它而不是你所拥有的:

    $poll_question->poll_choices()->save($poll_choices);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2013-04-06
      • 1970-01-01
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多