Laravel - 尝试访问不在选择中的属性时抛出异常

hap*_*set 2 php laravel eloquent laravel-5

例如,模型有很多属性,但在 select 中我只指定了几个属性。

$listings = Realty::select('city', 'mls', 'class_id')->get();
Run Code Online (Sandbox Code Playgroud)

如何使一个特质(prefebable)或类继承 Eloquent,如果我尝试访问不在 select 中的属性,它将抛出异常:

$propertyType = $listings[0]->property_type; // returns `null`, but I need 
                                             // RuntimeException or ErrorException
Run Code Online (Sandbox Code Playgroud)

jed*_*ylo 5

当您尝试读取 Eloquent 对象的属性时,Eloquent 会尝试按以下顺序从不同位置读取该值:

  • 从数据库中获取属性
  • 动态属性获取器
  • 关系

因此,如果您想在尝试访问上述任何内容中不存在的属性时获得异常,则需要重写模型中的最后一部分 - getRelationValue方法:

public function getRelationValue($key)
{
    if ($this->relationLoaded($key)) {
        return $this->relations[$key];
    }

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

    throw new \Exception;
}
Run Code Online (Sandbox Code Playgroud)

请记住,这不是面向未来的。如果 Eloquent 的未来版本更改了获取属性的实现方式,则可能需要更新上述方法的实现。

Laravel 5.0 更新

在 Laravel 5.0 中,覆盖Eloquent 模型中的getAttribute方法就足够了:

public function getAttribute($key)
{
    $inAttributes = array_key_exists($key, $this->attributes);
    if ($inAttributes || $this->hasGetMutator($key))
    {
        return $this->getAttributeValue($key);
    }

    if (array_key_exists($key, $this->relations))
    {
        return $this->relations[$key];
    }

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

    throw new \Exception;
}
Run Code Online (Sandbox Code Playgroud)