[英]Laravel relation displaying null on eager load
A Laravel relation is displaying null on eager load. Laravel 关系在急切加载时显示为空。 However, it works when the relation is accessed normally.但是,它在正常访问关系时起作用。
class Student extends Model
{
use SoftDeletes;
public $incrementing = false;
protected $primaryKey = 'id'; // or null
protected $guarded = [];
public function document()
{
return $this->hasOne('App\Model\Document');
}
public function contact()
{
return $this->hasOne('App\Model\Contact');
}
}
The contract relation returns null when I use the following.当我使用以下内容时,合同关系返回 null。
Student::with('contact')->get()
However it works when I do the following.但是,当我执行以下操作时它会起作用。 What could be the cause of this?这可能是什么原因?
$student = Student::findOrFail($id);
$contact = $student->contact;
Student::with('contact')->get();
returns a Collection
of Student
instances, which you can loop and access the contact
relationship:返回一个Student
实例的Collection
,您可以循环访问该实例并访问contact
关系:
$students = Student::with('contact')->get();
foreach($students AS $student){
dd($student->contact);
// Can be `null` or an instance of `Contact`
}
When you call Student::findOrFail($id);
当你调用Student::findOrFail($id);
, you're getting a single instance of Student
, which you can directly access contact
: ,您将获得Student
的单个实例,您可以直接访问contact
:
$student = Student::with('contact')->findOrFail($id);
dd($student->contact);
// Again, can be `null` or an instance of `Contact`
The with()
clause is eager loading, and doesn't do anything until you try to access $student->contact
, but due to the nature of hasOne()
, it can be null
. with()
子句是急切加载,在您尝试访问$student->contact
hasOne()
$student->contact
之前不会执行任何操作,但由于hasOne()
的性质,它可以为null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.