You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.5结合andersao/l5-repository实现通过问题仓库添加答案记录

如何在Laravel 5.5的l5-repository中通过QuestionRepository添加Answer记录

看起来你在尝试用andersao/l5-repository扩展包,通过QuestionRepository关联创建Answer记录,现在的代码里直接调用$this->repository->answer->create()是行不通的——因为仓库类本身不会自动绑定关联模型,我来一步步教你怎么正确实现:

1. 先确认模型间的关联关系

首先得确保Question和Answer模型的一对多关联是正确定义的:

在Question模型中定义关联

// app/Question.php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Question extends Model
{
    // 其他模型代码...
    
    public function answers()
    {
        return $this->hasMany(Answer::class);
    }
}

在Answer模型中定义反向关联

// app/Answer.php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Answer extends Model
{
    // 其他模型代码...
    
    public function question()
    {
        return $this->belongsTo(Question::class);
    }
}

2. 修正控制器的逻辑

你当前的代码没有先获取对应的Question实例,直接调用仓库的answer属性是无效的。需要先找到目标问题,再通过模型关联创建答案:

public function add_answer(AnswerAddRequest $request, $questionId)
{
    // 执行验证逻辑(你的验证代码没问题的话可以保留)
    $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_CREATE);
    
    // 通过仓库找到指定ID的Question实例
    $question = $this->repository->find($questionId);
    
    // 检查问题是否存在,不存在则返回404
    if (!$question) {
        abort(404, '指定的问题不存在');
    }
    
    // 通过模型关联创建Answer记录
    $answer = $question->answers()->create($request->only('content'));
    
    // 这里可以根据需求返回响应,比如重定向或JSON
    return redirect()->back()->with('success', '答案添加成功');
}

3. (可选)在仓库中封装添加答案的方法

如果你想把业务逻辑封装到仓库层,也可以在QuestionRepository中添加自定义方法:

// app/Repositories/QuestionRepository.php
use Prettus\Repository\Eloquent\BaseRepository;
use App\Question;

class QuestionRepository extends BaseRepository
{
    public function model()
    {
        return Question::class;
    }
    
    // 自定义添加答案的方法
    public function addAnswer($questionId, array $answerData)
    {
        $question = $this->find($questionId);
        if (!$question) {
            throw new \Exception('问题不存在');
        }
        
        return $question->answers()->create($answerData);
    }
}

然后在控制器中调用这个方法:

public function add_answer(AnswerAddRequest $request, $questionId)
{
    $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_CREATE);
    
    $answer = $this->repository->addAnswer($questionId, $request->only('content'));
    
    return redirect()->back()->with('success', '答案添加成功');
}

4. 配置对应的路由

最后要确保路由能正确传递问题ID:

// routes/web.php
Route::post('/questions/{questionId}/answers', 'QuestionController@add_answer')->name('questions.answers.add');

内容的提问来源于stack exchange,提问作者Kvlknctk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:32:20