如何将用户ID保存为用户模型的关系?

时间:2017-02-26 00:06:42

标签: php laravel

我试图将user_id作为'外键'使用Auth::user()->id进入问题表。

我的模特:

public function user(){
        return $this->belongsTo('App\User');
    }
    //saves post
    public function saveQuestion(buildQuestion $buildQuestion, $userId){
        $buildQuestion->user_id = $userId;
        return $this->user()->save($buildQuestion);
    }

我的控制器:

public function submitQuestion(Request $request,buildQuestion $buildQuestion){

        $answers = new buildQuestion($request->all());


        if (Auth::user()){

            $buildQuestion->saveQuestion($answers, Auth::user()->id);

        }else if(Auth::guest()){
            abort (403, 'Not Logged In');

        }
    }

我不认为我应该将buildQuestion作为参数传递给模型。

我提交表单时收到此错误:调用未定义的方法Illuminate \ Database \ Query \ Builder :: save()

1 个答案:

答案 0 :(得分:0)

Class BuildQuestion{
    public function user(){
        return $this->belongsTo('App\User');
    }
...

  Class User{
    public function buildQuestion(){
        return $this->hasMany('App\BuildQuestion');
    }
...

控制器

public function submitQuestion(Request $request){

    $answers = new buildQuestion($request->all());


    if (Auth::user()){

        Auth::user()->buildQuestion()->create($answers);

    }elseif(Auth::guest()){
    //suggestion redirect to login page
    //return redirect('/login');
        abort (403, 'Not Logged In');

    }
}