簡體   English   中英

Laravel 關系在急切加載時顯示為空

[英]Laravel relation displaying null on eager load

Laravel 關系在急切加載時顯示為空。 但是,它在正常訪問關系時起作用。

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');
    }
}

當我使用以下內容時,合同關系返回 null。

Student::with('contact')->get()

但是,當我執行以下操作時它會起作用。 這可能是什么原因?

$student = Student::findOrFail($id);
$contact = $student->contact;

Student::with('contact')->get(); 返回一個Student實例的Collection ,您可以循環訪問該實例並訪問contact關系:

$students = Student::with('contact')->get();
foreach($students AS $student){
  dd($student->contact); 
  // Can be `null` or an instance of `Contact`
}

當你調用Student::findOrFail($id); ,您將獲得Student的單個實例,您可以直接訪問contact

$student = Student::with('contact')->findOrFail($id);
dd($student->contact);
// Again, can be `null` or an instance of `Contact`

with()子句是急切加載,在您嘗試訪問$student->contact hasOne() $student->contact之前不會執行任何操作,但由於hasOne()的性質,它可以為null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM