Eloquent relationship返回错误试图在Laravel 5.4中获取非对象的属性

时间:2017-07-02 18:30:08

标签: php laravel-5.4

我已经经历了类似的问题,但我们无法看到我做错的地方或地点。

所以我已经建立了员工和任务之间的关系

任务模型

class Task extends Model
{
    public function employee()
    {
        return $this->belongsTo(Employee::class, 'employee_id');
    }
}

Empoyee模型

public function tasks()
{
    return $this->hasMany(Task::class);
}

我的任务表结构使用employee_id作为外键

public function up()
{
    Schema::create('tasks', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('employee_id')->unsigned();
$table->foreign('employee_id')->references('id')->on('employees')->onDelete('cascade');
        $table->string('title');
        $table->string('description');
        $table->string('priority');
        $table->date('begin');
        $table->date('end');
        $table->timestamps();
    });
}

在我看来,我试图首先将该任务列表与员工一起返回但我得到错误"试图获取非对象的属性&#34 34;

@foreach ($allTask as $task)
    <tr>
        <td>{{ $task->priority }}</td>
        <td>{{ $task->title }}</td>
        <td>{{ ucfirst($task->employee->firstname) }} {{" "}} {{ ucfirst($task->employee->lastname) }}</td>
        <td>{{ $task->end }}</td>
    </tr>
@endforeach

当我用我的控制器转储并死掉数据时,

public function index()
{
    $allTask = Task::with('employee')->limit(5)->get();

    /*return view('home', compact('allTask'));*/

    dd($allTask);
}

我能够看到这个

`#original: array:9 [▼
    "id" => 1
    "employee_id" => 2
    "title" => "Roaster"
    "description" => "Submission of work roaster has commenced and you are expected to submit before the due date"
    "priority" => "high"
    "begin" => "2017-06-26"
    "end" => "2017-06-30"
    "created_at" => "2017-06-26 22:32:39"
    "updated_at" => "2017-06-26 22:32:39"
  ]`

我在哪里弄错了?

1 个答案:

答案 0 :(得分:0)

您返回的tasks中的某个可能没有您要显示的所有字段, 更改模板如下:

@foreach ($allTask as $task)
    <tr>
        <td>{{ isset($task->priority) ? $task->priority : 'no priority !'  }}</td>
        <td>{{  isset($task->title) ? $task->title : 'no title!'  }}</td>
        <td>{{  isset($task->employee->firstname) ?  ucfirst($task->employee->firstname) : 'no first name!' }} {{" "}} {{ 
 isset($task->employee->lastname) ? ucfirst($task->employee->lastname) : 'no last name!' }}</td>
        <td>{{  isset($task->end) ? $task->end : 'no end!'  }}</td>
    </tr>
@endforeach

<强>更新

您正在以错误的方式打印employee

我们可以通过两种方式来实现这一目标:

1-

$allTask = Task::with('employee')->limit(5)->get();

isset($task->employee[0]) ?  ucfirst($task->employee[0]->firstname) : 'empty'

2-

$allTask = Task::with(['employee' => function($q){
   $q->first();
}])->limit(5)->get();

isset($task->employee) ?  ucfirst($task->employee->firstname) : 'empty'