【发布时间】:2020-10-18 16:43:21
【问题描述】:
Laravel 7 和 2 表:comp、计算机。
我想在视图 index.blade.php 中显示计算机的名称,例如DELL, IBM, LENOWO 而不是这个名字的id。 从计算机表中检索计算机名称的 foreach 语法应该是什么样的。
当您添加一台新 PC 时,下拉列表应该是什么样的?
class CreateCompTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('comp', function (Blueprint $table) {
$table->id();
$table->integer('name_id')->unsigned();
$table->string('number');
$table->string('year');
$table->timestamps();
$table->foreign('name_id')->references('id')->on('computers')
->onDelete('cascade');
});
}
台式电脑
class CreateComputersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('computers', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
CompControllers
namespace App\Http\Controllers;
use App\Comp;
use Illuminate\Http\Request;
class CompController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$comp = Comp::latest()->paginate(5);
return view('comp.index',compact('comp'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('comp.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name_id' => 'required',
'number' => 'required',
'year' => 'required',
]);
comp::create($request->all());
return redirect()->route('comp.index')
->with('success','xxx.');
}
/**
* Display the specified resource.
*
* @param \App\Comp $comp
* @return \Illuminate\Http\Response
*/
public function show(Comp $comp)
{
return view('comp.show',compact('comp'));
}
查看 index.blade.php
@extends('comp.layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Comp</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('comp.create') }}"> Add comp</a>
</div>
</div>
</div>
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
<table class="table table-bordered">
<tr>
<th>L.p</th>
<th>Name comp</th>
<th>Number comp</th>
<th>Year</th>
<th width="250px">Acction</th>
</tr>
@foreach ($comp as $comp)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $comp->name_id }}</td>
<td>{{ $comp->number }}</td>
<td>{{ $comp->year }}</td>
<td>
<form action="{{ route('comp.destroy',$comp->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('comp.show',$comp->id) }}">View</a>
<a class="btn btn-primary" href="{{ route('comp.edit',$comp->id) }}">Edit</a>
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
@endforeach
</table>
@endsection
【问题讨论】: