【问题标题】:Laravel 5 Eager Loading not workingLaravel 5急切加载不起作用
【发布时间】:2015-03-13 15:39:54
【问题描述】:

我查看了很多有这个问题的搜索结果,但我无法让它工作。

用户模型

<?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
  • 并且......它的解决方案......感谢 lukasgeiter!

标签: php loading laravel-5 eager


【解决方案1】:

您必须将关系方法声明为public

这是为什么呢?我们来看看with()方法:

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

    $instance = new static;

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

由于该方法是从静态上下文中调用的,它不能只调用$this-&gt;Person()。相反,它会创建模型的一个新实例并创建一个查询构建器实例,然后调用 with 以此类推。最后,关系方法必须可以从模型外部访问。这就是为什么可见性需要为public

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    相关资源
    最近更新 更多