簡體   English   中英

Laravel 5渴望加載無法正常工作

[英]Laravel 5 Eager Loading not working

我看到許多搜索結果都遇到了這種麻煩,但我無法使其正常工作。

用戶模型

<?php namespace Module\Core\Models;

class User extends Model {

(...)

protected function Person() {
    return $this->belongsTo( 'Module\Core\Models\Person', 'person_id' );
}

(...)

人模型

<?php namespace Module\Core\Models;

class Person extends Model {

(...)

protected function User(){
    return $this->hasOne('Module\Core\Models\User', 'person_id');
}

(...)

現在,如果我使用User :: find(1)-> Person-> first_name其工作。 我可以從用戶模型中獲得人員關系。

但是.. User :: with('Person')-> get()失敗,並調用了未定義的方法Illuminate \\ Database \\ Query \\ Builder :: Person()

我在做什么錯? 我需要所有用戶及其個人信息的集合。

您必須將關系方法聲明為public

這是為什么? 讓我們看一下with()方法:

public static function with($relations)
{
    if (is_string($relations)) $relations = func_get_args();

    $instance = new static;

    return $instance->newQuery()->with($relations);
}

由於該方法是從靜態上下文中調用的,因此不能僅調用$this->Person() 相反,它創建模型的新實例,並創建一個查詢生成器實例並調用with對等。 最后,必須從模型外部訪問關系方法。 這就是為什么可見性需要public

暫無
暫無

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

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