【问题标题】:Laravel attach returns undefined method for belongsToMany relationshipLaravel attach 为 belongsToMany 关系返回未定义的方法
【发布时间】:2017-09-28 21:10:40
【问题描述】:

我想创建一个包含许多调查的问题。在问题模型中:

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
{
}

问题存储库:

interface QuestionsRepository extends BaseRepository
{
}

【问题讨论】:

  • 根据你的代码,可以试试$question = $this->questions->create($request->all());$question->surveys()->attach($request->surveys);
  • EloquentBaseRepository 长什么样子?
  • @HanlinWang 回复是(1/1) BadMethodCallException Call to undefined method Illuminate\Database\Query\Builder::surveys‌​()
  • @Maraboc 这是 AsgardCMS 中的默认设置,所以github.com/AsgardCms/Core/blob/master/Repositories/Eloquent/…
  • 能否也显示 QuestionsRepository 的代码?

标签: php laravel


【解决方案1】:

正如对主要帖子的回复中所解释的 - 构造函数将 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

【讨论】:

    猜你喜欢
    • 2014-11-23
    • 1970-01-01
    • 2014-04-25
    • 2020-06-03
    • 2016-12-09
    • 2018-10-16
    • 2014-01-12
    • 2018-05-19
    • 2021-02-05
    相关资源
    最近更新 更多