我的迁移
Schema::create('tickets', function(Blueprint $table)
{
$table->increments('id');
$table->text('subject');
$table->text('body');
$table->integer('author_id')->unsigned();
$table->timestamps();
});
Schema::table('tickets', function($table)
{
$table->foreign('author_id')->references('id')->on('users');
});
关系
public function createdTickets()
{
return $this->hasMany('App\Ticket');
}
public function author(){
return $this->belongsTo('App\User', 'author_id');
}
和存储方法
public function store(TicketRequest $request)
{
$ticket = new Ticket($request->all());
Auth::user()->createdTickets()->save($ticket);
return redirect('tickets');
}
当我尝试保存新票证时,我收到此错误消息
QueryException in Connection.PHP line 624:
sqlSTATE[HY000]: General error: 1 table tickets has no column named user_id (sql: insert into “tickets” (“subject”, “body”, “user_id”, “updated_at”, “created_at”)
除关系外,我还需要在哪里指定FK?
解决方法:
您需要在两种关系方法中指定所需的列名.
public function createdTickets()
{
return $this->hasMany('App\Ticket', 'author_id');
}