Laravel 从输入中保存关系

Laravel save relation from input

我有以下关系:

门票型号:

public function status()
{
    return $this->belongsTo('App\Status');
}

状态模型:

public function tickets()
{
    return $this->hasMany('App\Ticket');
}

TicketController 函数 create()

$statuses = Status::get()->lists('name', 'id');
return view('backend.tickets.create', compact('statuses'));

查看create.blade.php

{!! Form::select('status', $statuses, null, ['class' => 'form-control'])  !!}

TicketController 函数存储()

// Get the selected status from input and find the Status
   $status = Status::where('id', '=', $request['status'])->first();

// Associate status to ticket
    $ticket->status()->associate($status);

它不起作用。在数据库中,我的票 table 中的 status_id 始终为空。

你能帮帮我吗?

谢谢!

关联后,你应该保存 $ticket:

// Get the selected status from input and find the Status
$status = Status::where('id', '=', $request['status'])->first();
// or better
$status = Status::find($request['status']);

// Associate status to ticket
$ticket->status()->associate($status);

// Save the ticket
$ticket->save();