我想存储从选择标记中拾取的另一个表中的数据
数据来自另一个模型(汇款模型),我想选择汇款的名称并获取其ID,以便将其存储到Bills表中
--Bill Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Bill;
use App\Models\Remittent;
class BillController extends Controller
{
public function create(){
$remittents = Remittent::select('remittent')->get();
return view('bills.create', compact('remittents'));
}
}
--Bill Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Bill extends Model
{
protected $table = 'bills';
protected $fillable = ['number','remittent_id'];
protected $guarded = ['id'];
public function remittent()
{
return $this->belongsTo(Remittent::class);
}
}
--Remittent Model:
?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Remittent extends Model
{
protected $table = 'remittents';
protected $fillable = ['remittent'];
protected $guarded = ['id'];
public function bill()
{
return $this->hasMany(Bill::class);
}
}
--The view:
@extends('master')
@section('content')
<h2>Add a bill</h2>
@if($errors->all())
<div class="alert alert-danger">
@foreach($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</div>
@endif
<form action="{{route('bills.store')}}" method="post">
@csrf
<div class="form-group">
<label>Bill number</label>
<input type="number" name="number" id="number" class="form-control">
</div>
<div class="form-group">
<label>Remittent</label>
<select class="form-control">
@foreach($remittents as $remittent)
<option value="$remittent->id">{{ $remittent->remittent}}</option>
@endforeach
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Add a bill</button>
</div>
</form>
@endsection
问题是,在MySql表上,存储方法期望的值是整数值,并且当我从select标记中选择选项时,它是一个String值,因此我想知道如何从中获取ID从select标签中选择汇款表时。
谢谢。
答案 0 :(得分:0)
您的刀片服务器模板在以下行中有一个错误:
<option value="$remittent->id">{{ $remittent->remittent}}</option>
您需要将所有变量用法都用大括号括起来,无论用户看到的是什么还是其不可见标记。因此,只需将其更改为以下内容即可:
<option value="{{ $remittent->id}} ">{{ $remittent->remittent }}</option>
然后在您的控制器中,同时选择id
和remittant
:
Remittant::select(['id', 'remittant']) - >get();