我尝试使用laravel 5.2查询在表格中创建一个新行。
我的表"答案"有5列 - > answer_id (auto_inc), people_id(sames as Auth::id), question_id('Integer'), answer(input field), created_at(timestamp())
answercontroller文件:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;
class answerController extends Controller
{
public function store(Requests\answerAddRequest $request)
{
Auth::user()->questions('question_id')->answers()->create($request->all());
}
}
回答模型类
class answers extends Model
{
protected $table='answers';
protected $fillable='answer';
protected $primaryKey='answer_id';
public function setUpdatedAtAttribute($value) {}
public function User()
{
return $this->belongsTo('App\User');
}
public function questions()
{
return $this->belongsTo('App\questions','people_id');
}
}
我无法在答案表中添加新行,因为我无法理解如何在表格中传递question_id
问题模型类
class questions extends Model
{
protected $table='questions';
protected $primaryKey='question_id';
protected $fillable = [
'question', 'created_at','details'
];
//protected $hidden=['question_id'];
public function setUpdatedAtAttribute($value) {}
public function User() {
return $this->belongsTo('App\User');
}
public function answers()
{
return $this->hasMany('App\answers','answer_id');
}
public function scopefetchQuestions($query) {
return $query->select('question','question_id')->where('people_id','=',Auth::id())->get();
}
}
使用当前代码抛出此错误:
BadMethodCallException in Builder.php line 2405:
Call to undefined method Illuminate\Database\Query\Builder::answers()
我该如何解决?
答案 0 :(得分:1)
请试试这个:
class answerController extends Controller
{
public function store(Requests\answerAddRequest $request)
{
$answer = App\Answer::create($request->all());
Auth::user()->questions()->where('question_id', $request->get('question_id'))->first()->answers()->save($answer);
}
}
还要将外键添加到$fillable
数组中
https://laravel.com/docs/5.2/eloquent#inserting-and-updating-models
https://laravel.com/docs/5.2/eloquent-relationships#inserting-related-models