[英]Undefined property: Illuminate\Database\Eloquent\Collection::$name Laravel 5.3
[英]laravel 5.3 : Undefined property: Illuminate\Database\Eloquent\Collection Error
我有一個表,稱為Doctor(staff_id,specialization),另一張表是staff(staff_id,password,名稱,電子郵件,地址,部門,sub_department,post),在醫生表中,外鍵staff_id
是對職員表的staff_id
屬性的staff_id
。 我不知道為什么我使用Laravel 5.3出現此錯誤,請幫幫我。
這是我的“職員模型”
namespace App;
use Illuminate\Database\Eloquent\Model;
class Staff extends Model
{
protected $table = 'Staff';
public function doctor(){
return $this->hasOne('App\Doctor');
}
}
這是我的“醫生模型”
namespace App;
use Illuminate\Database\Eloquent\Model;
class Doctor extends Model
{
protected $table = 'Doctor';
public function staff(){
return $this->belongsTo('App\Staff');
}
}
這是管制員
use App\Doctor;
use App\Staff;
class PageController extends Controller
{
public function getIndex(){
$doctor = Doctor::all();
return view('pages.welcome')->withDoctor($doctor);
}
}
這是我使用它的welcome.blade.php
<pre>
<tr>
<td>{{ $doctor->staff->name }}</td>
</tr>
</pre>
當我運行它時,我得到了這個錯誤:
150a6b9d586ccbe6225ed748a7eb8dfc842ce323.php第26行中的ErrorException:未定義的屬性:Illuminate \\ Database \\ Eloquent \\ Collection :: $ staff(視圖:C:\\ wamp \\ www \\ se \\ resources \\ views \\ pages \\ welcome.blade.php)
嘗試像這樣從控制器傳遞數據:
public function getIndex(){
$doctor = Doctor::all();
return view('pages.welcome')->with('doctor', $doctor);
}
Your controller should be.
use App\Doctor;
use App\Staff;
class PageController extends Controller
{
public function getIndex(){
$doctor = Doctor::all();
return view('pages.welcome',compact('doctor'));
}
}
Your views should be-
<pre>
@foreach($doctor as $doctors)
<tr>
<td>{{ $doctors->name }}</td>
</tr>
@endforeach
</pre>
謝謝大家的幫助,我終於找到了解決該錯誤的方法,這里有一些問題可以幫助您-1。在模型中,我們應該告訴模型主鍵,例如“ STAFF”模型將類似於命名空間App;
use Illuminate\Database\Eloquent\Model;
class Staff extends Model
{
protected $primarykey = 'staff_id';
protected $table = 'Staff';
public function doctor(){
return $this->hasOne('App\Doctor');
}
}
現在我們可以默認將主鍵稱為“ id”。
我們也必須為“ DOCTOR”模型更改此名稱空間App;
use Illuminate\Database\Eloquent\Model;
class Doctor extends Model
{
protected $primarykey = 'staff_id';
protected $table = 'Doctor';
public function staff(){
return $this->belongsTo('App\Staff');
}
}
現在我們的控制器應該像
使用App \\ Doctor;
使用App \\ Staff;
類PageController擴展了控制器{公共函數getIndex(){$ doctor = Doctor :: find(id); 返回視圖('pages.welcome')-> withDoctor($ doctor); }}
現在在我的welcome.blade.php中應該像-
\n \n {{$ doctor-> staff-> name}}\n \n
這正在工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.