我试图将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()
答案 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');
}
}