从视图上的外键获取数据 (Laravel 5.6)

Getting data from foreign key on view (Laravel 5.6)

我已经搜索了答案,但找不到任何可以解决我的问题的答案。

我有 2 个 table:phonesphone_types。第一个有一个与 phone_types 主键关联的外键。我想通过 phone 对象在视图中显示 phone_type 的名称。类似于 $phone->phone_type->name

我的代码生成此错误:Trying to get property of non-object (View: /home/ablono/dev/MisServices/resources/views/painel/phones/home.blade.php)

我的代码如下。

phone_types 米拉table:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePhoneTypesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('phone_types', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 20);
            $table->string('description', 30);
            $table->timestamps();
        });
    }
/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('phone_types');
}

} ```

phone秒迁移table:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePhonesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('phones', function (Blueprint $table) {
            $table->increments('id');
            $table->string('ddd')->default('13');
            $table->string('number', 20);
            $table->integer('phone_type_id')->unsigned();
            $table->foreign('phone_type_id')
                ->references('id')
                ->on('phone_types')
                ->onDelete('cascade');
            $table->timestamps();
        });

        Schema::create('phone_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('phone_id')->unsigned();
            $table->integer('user_id')->unsigned();

            $table->foreign('phone_id')
                ->references('id')
                ->on('phones')
                ->onDelete('cascade');

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('phone_user');
        Schema::dropIfExists('phones');
    }
}

我没有在 PhoneType 模型上编写任何代码,但这里是代码:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class PhoneType extends Model
{
    //
}

Phone 型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    public function users()
    {
        return $this->belongsToMany(\App\User::class);
    }

    public function phoneType()
    {
        return $this->hasMany(\App\PhoneType::class);
    }
}

发送到视图的方法:

public function index()
    {
        $phones = Phone::all();

        return view('painel.phones.home', compact('phones'));
    }

列出数据的部分视图:

<table class="table">
            <thead>
                <th>ID</th>
                <th>DDD</th>
                <th>Número</th>
                <th>Tipo de Telefone</th>
                <th width="150px">Ações</th>
            </thead>
            <tbody>
                @foreach($phones as $phone)
                    <tr>
                        <div class="loading"></div>
                        <td>{{ $phone->id }}</td>
                        <td>{{ $phone->ddd }}</td>
                        <td>{{ $phone->number }}</td>
                        <td>{{ $phone->phone_type_id->name }}</td>

                        <td>
                            <a href="/admin/phone/users/{{ $phone->id }}"><i class="fa fa-lg fa-phone" title="Visualizar usuários que usam {{ $phone->number }}"></i></a>
                            <a href="/admin/phone/edit/{{ $phone->id }}"><i class="fa fa-lg fa-pencil" title="Editar {{ $phone->number }}"></i></a>
                            <a href="/admin/phone/delete/{{ $phone->id }}"><i class="fa fa-lg fa-times" title="Excluir {{ $phone->number }}"></i></a>
                            <a href="/admin/phone/view/{{ $phone->id }}"><i class="fa fa-lg fa-eye" title="Visualizar {{ $phone->number }}"></i></a>
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>

将您的关系更改为 belongsTo()

public function phoneType()
{
    return $this->belongsTo(\App\PhoneType::class, 'phone_type_id');
}

并且在view

 <td>{{ $phone->phone_type->name }}</td>

请检查您的 eloquent 模型关系。访问 eloquent 属性 就像 . $main-model->$sub-model(您要访问的模型的方法名)->属性 注意:访问方法时请将方法名转换为snake case