0

我用这个麻烦查看了许多搜索结果,但我无法让它工作。

用户模型

<?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() 失败

我做错了什么?我需要收集所有用户及其个人信息。

4

1 回答 1

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->Person(). 相反,它创建模型的一个新实例并创建一个查询构建器实例并调用with它等等。最后,关系方法必须可以从模型外部访问。这就是为什么需要可见性public

于 2015-03-13T17:10:39.813 回答