Laravel - 预加载 - 尝试获取 属性 的非对象
Laravel - Eager Loading - Trying to get property of non-object
抱歉这个菜鸟问题,但我无法进行预加载工作,而是得到:Trying to get property of non-object
在我看来(index.blade.php
下面)。
用户table
id | first_name | other_columns
学分 table
id | recipient | other_columns
recipient
来自用户 table.
id
Credit.php
class Credit extends Model {
public function recipient() {
return $this->belongsTo('App\User', 'recipient');
}
}
User.php
class User extends Model {
public function credits() {
return $this->hasMany('App\Credit', 'recipient');
}
}
CreditController.php
class CreditController extends Controller {
public function index() {
$credits = Credit::with('recipient')->get();
return view('pages.credits.index')->withCredits($credits);
}
}
index.blade.php
@foreach($credits as $credit)
{{ $credit->recipient->first_name }}
@endforeach
我错过了什么?
我通过更改 Credit
模型解决了这个问题:
public function recipient() {}
进入
public function user() {}
抱歉这个菜鸟问题,但我无法进行预加载工作,而是得到:Trying to get property of non-object
在我看来(index.blade.php
下面)。
用户table
id | first_name | other_columns
学分 table
id | recipient | other_columns
recipient
来自用户 table.
id
Credit.php
class Credit extends Model {
public function recipient() {
return $this->belongsTo('App\User', 'recipient');
}
}
User.php
class User extends Model {
public function credits() {
return $this->hasMany('App\Credit', 'recipient');
}
}
CreditController.php
class CreditController extends Controller {
public function index() {
$credits = Credit::with('recipient')->get();
return view('pages.credits.index')->withCredits($credits);
}
}
index.blade.php
@foreach($credits as $credit)
{{ $credit->recipient->first_name }}
@endforeach
我错过了什么?
我通过更改 Credit
模型解决了这个问题:
public function recipient() {}
进入
public function user() {}