拉拉维尔雄辩属于



我在使用 Laravel 4.1 时遇到了问题。我在两个表之间做了一个关系 oneToMany。当我把这段代码放在我的视图中时,我没有任何问题:

{{ $admin->admin_role()->first()->name }}

但是当我试图把它缩短时,因为 laravel 文档是这样说的:

{{ $admin->admin_role->name }}

我有一个

Trying to get property of non-object

我知道这不是一个大问题,因为我可以使用第一个选项,但如果有人有任何想法,我很想阅读它们!

谢谢大家

在我的项目中,1 个角色有许多管理员

如果一个角色有许多用户,那么即使只有一个admin它也会返回一个集合,因此以下代码返回一个models集合,如果不指定模型,则无法从集合中获取任何属性:

$admin->admin_role();

所以你可以使用(已经知道):

$admin->admin_role()->first()->name;
$admin->admin_role()->last()->name;
$admin->admin_role()->find(1)->name; // Assumed 1 is id (primary key)
$admin->admin_role()->get(0); // it's first, equivalent to first()
$admin->admin_role()->get(1); // second item from collection

这是使用模型实例的 getter 时的代码。

https://github.com/illuminate/database/blob/master/Eloquent/Model.php#L2249

public function getAttribute($key)
{
    $inAttributes = array_key_exists($key, $this->attributes);
    // If the key references an attribute, we can just go ahead and return the
    // plain attribute value from the model. This allows every attribute to
    // be dynamically accessed through the _get method without accessors.
    if ($inAttributes || $this->hasGetMutator($key))
    {
        return $this->getAttributeValue($key);
    }
    // If the key already exists in the relationships array, it just means the
    // relationship has already been loaded, so we'll just return it out of
    // here because there is no need to query within the relations twice.
    if (array_key_exists($key, $this->relations))
    {
        return $this->relations[$key];
    }
    // If the "attribute" exists as a method on the model, we will just assume
    // it is a relationship and will load and return results from the query
    // and hydrate the relationship's value on the "relationships" array.
    $camelKey = camel_case($key);
    if (method_exists($this, $camelKey))
    {
        return $this->getRelationshipFromMethod($key, $camelKey);
    }
}

第一个条件是false admin_role因为不是属性,并且通常关系没有突变器。回退到第二个块

第二个块false与第一个条件相同,因为您没有使用预先加载。回退到第三个条件。

在第三个条件下

    $camelKey = camel_case($key);
    if (method_exists($this, $camelKey))
    {
        return $this->getRelationshipFromMethod($key, $camelKey);
    }

$camelKey = camel_case("admin_role"); // "adminRole"

并且adminRole在您的模型中不存在(因为您定义了admin_role),因此$admin->admin_role()返回null并且null值不是对象。

最新更新