Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/230.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel getAttribute($key)作为自己的模型函数_Php_Laravel_Eloquent - Fatal编程技术网

Php Laravel getAttribute($key)作为自己的模型函数

Php Laravel getAttribute($key)作为自己的模型函数,php,laravel,eloquent,Php,Laravel,Eloquent,我正在我的一个模型中使用getAttribute($key)函数 功能: 该函数返回我的模型的所有属性,并将关系($this->project)中的属性添加到模型中 我的问题是,每当我使用模型时,这个函数都会运行。 是否可以将其包装到自己的函数中,例如: 型号: 控制器: $projectTranslation->myown函数($key)像什么?“该函数在我每次使用模型时都会运行”怎么办?@Bromber是的,我试过了,但是可选($this->project)->getAttribute($k

我正在我的一个模型中使用
getAttribute($key)
函数

功能:

该函数返回我的模型的所有属性,并将关系(
$this->project
)中的属性添加到模型中

我的问题是,每当我使用模型时,这个函数都会运行。 是否可以将其包装到自己的函数中,例如:

型号:

控制器:


$projectTranslation->myown函数($key)

像什么?“该函数在我每次使用模型时都会运行”怎么办?@Bromber是的,我试过了,但是
可选($this->project)->getAttribute($key)
不再起作用了。@EsTeAa它应该结合我模型的所有属性键和关系
$this->project
。每次使用该模型时它运行的实际问题是什么?在您的控制器中,您可以使用刚才提供的确切代码吗?例如,在控制器中调用$model->someProperty,如果模型具有非null的'someProperty',它将返回它,如果没有,它将返回$model->project->someProperty(具有null回退)?@aj认为问题在于
getAttribute($key)
在我将模型返回到视图时自动运行,我不希望每次都出现这种行为,因为我正在使用Livewire编辑模型。当我在
myOwnFunction($key)
中包装所有内容并使用此
$projectTranslation->myOwnFunction($key)在我的控制器中,当某个键为null时,模型不会返回“$model->project->someProperty”。
public function getAttribute($key)
{
    return parent::getAttribute($key) ??
       optional($this->project)->getAttribute($key);
}
public function myOwnFunction($key)
{
    return parent::getAttribute($key) ??
       optional($this->project)->getAttribute($key);
}