Laravel - 用户外键导致尝试获取非对象

时间:2017-02-28 09:23:23

标签: php mysql laravel

简介

亲爱的堆叠器,

我目前正在开展一个小项目,而不是花费我一大笔时间。这是低效的生产,因此我想解决我的问题。那么,问题是什么?

问题

我正在尝试访问$ hour变量中的属性。此属性是User模型的“名称”字段(Laravel的默认安装提供给您的模型)。用户和小时模型通过Hour表中的“werknemer_id”链接在一起,该表引用User表中的“id”字段。但是,当我尝试调用用户时,它会返回“尝试获取非对象属性”错误。

数据库关系 https://gyazo.com/5a39f76d7fe6e297551e74a46a8def7c

用户模型

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Hour;

class User extends Authenticatable
{
use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password',
];

public function Hours() {
    return $this->hasMany(Hour::class);
}

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];
}

小时模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\User;

class Hour extends Model
{
protected $fillable = [
    'id', 'werknemer_id', 'weeknummer', 'dag', 'uren', 'toelichting',
];

public function User() {
    return $this->belongsTo(User::class);
}
}

小时迁移表

<?php

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

class CreateHoursTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('hours', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('werknemer_id')->unsigned();
        $table->integer('weeknummer');
        $table->string('dag');
        $table->integer('uren');
        $table->string('toelichting');
        $table->rememberToken();
        $table->timestamps();
    });

    Schema::table('hours', function (Blueprint $table)
    {
        $table->foreign('werknemer_id')->references('id')->on('users');   
    });
}

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

视图

<a href="{{ url('/uren/create') }}">Voeg je uren toe</a>
<br/>
<table class="display table table-bordered table-condensed table-responsive dynamic-table">
    <thead>
        <tr>
            <th>Werknemer</th>
            <th>Week</th>
            <th>Dag</th>
            <th>Aantal uren</th>
            <th>Toelichting</th>
        </tr>
    </thead>

    <tbody>


    enter code here


        @foreach($hours as $hour)
        <tr class="clickable-row" data-url="/uren/{{ $hour->id }}">
            {{dd($hour)}}
            <td>{{ $hour->User->name}}</td>
            <td>{{ $hour->weeknummer }}</td>
            <td>{{ $hour->dag }}</td>
            <td>{{ $hour->uren }}</td>
            <td>{{ $hour->toelichting }}</td>
            <td><a href="{{ url('/uren', array('id' => $hour->id)) }}">Laat zien</td>
            <td><a href="{{ url('/uren/' . $hour->id . '/edit') }}">Bijwerken</a></td>
            {!! Form::open(array('route' => array('uren.destroy', $hour->id), 'method' => 'delete')) !!}
            <td><button class="btn btn-danger"  data-toggle="confirmation"   type="submit"><i class="fa fa-times"></i>Verwijder</button></td>

            {!! Form::close() !!}
           </tr>
           @endforeach

    </tbody>

    </table>
    <a href="/home">Keer terug naar het dashboard.</a>

视图,每小时dd'd

Hour {#200 ▼
  #fillable: array:6 [▼
    0 => "id"
    1 => "werknemer_id"
    2 => "weeknummer"
    3 => "dag"
    4 => "uren"
    5 => "toelichting"
  ]
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:9 [▼
    "id" => 1
    "werknemer_id" => 1
    "weeknummer" => 5
    "dag" => "Wednesday"
    "uren" => 5
    "toelichting" => ""
    "remember_token" => null
    "created_at" => "2017-02-01 08:56:10"
    "updated_at" => "2017-02-01 08:56:10"
  ]
  #original: array:9 [▼
    "id" => 1
    "werknemer_id" => 1
    "weeknummer" => 5
    "dag" => "Wednesday"
    "uren" => 5
    "toelichting" => ""
    "remember_token" => null
    "created_at" => "2017-02-01 08:56:10"
    "updated_at" => "2017-02-01 08:56:10"
  ]
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #guarded: array:1 [▼
    0 => "*"
  ]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  +exists: true
  +wasRecentlyCreated: false
}

如果省略dd的实际结果

https://gyazo.com/73a83f411728084b5b09e806132ed76e?token=2a47870927ce239b03763c8dc24384a5

1 个答案:

答案 0 :(得分:0)

问题在于您的命名。 Laravel有一个它希望你遵循的命名约定,如果你不这样做,你必须让系统知道。

在你的小时模型中,你有这样的用户功能:

    public function User() {
      return $this->belongsTo(User::class);
    }

它希望你的外键是user_id而不是werknemer_id。要解决此问题,请将id添加为第二个arg

    public function User() {
      return $this->belongsTo(User::class, 'werknemer_id');
    }

    public function werknemer() {
      return $this->belongsTo(User::class);
    }