【问题标题】:Laravel 7. How to fetch records from various tables using foreign key in laravel?Laravel 7. 如何在laravel中使用外键从各个表中获取记录?
【发布时间】: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

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    Comp 模型上,建立belongsTo 关系:

    public function computer()
    {
        return $this->belongsTo('App\Computer', 'name_id');
    }
    

    现在您可以通过刀片访问此关系,如下所示:

    @foreach($comp as $comp)
      <tr>
         <td>{{ $comp->computer->name }}</td>
      </tr>
    @endforeach
    

    【讨论】:

    • 不幸的是,当我尝试查看视图时,出现一条消息:ErrorException Trying to get property 'computer' of non-object (View: C:\xampp\htdocs\laravel7\resources\views \comp\index.blade.php)
    • 我认为您正在尝试显示模型的值为 null 检查您的数据库
    • 非常感谢您的帮助。它可以正常工作。在添加新计算机时,我仍然有从下拉列表中选择计算机的请求。
    猜你喜欢
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2021-03-17
    • 2018-12-08
    • 2018-05-14
    • 2019-02-27
    • 1970-01-01
    • 2019-04-25
    相关资源
    最近更新 更多