Laravel模型关系-更改为mutator,而无需更改cotrollers中的任何内容

问题描述 投票:0回答:1

我有2个表格,估计值和模型。两者之间存在一对一的关系。我想将模型名称从模型表移至估计表。这将通过我必须自己编写的脚本来完成。建立数据库的方式是错误的,由于许多原因,我不需要在此处指定。模型表只有两列-ID和名称。

我在许多控制器中都访问了此关系,并在我的应用程序中查看了所有内容:

$estimate->model_info->name

因此,我将同时保留模型表(无记录)和Model.php模型,将旧代码保留在控制器和视图中,但是访问模型名称的新代码将只是:

$estimate->name

在Estimate.php模型中,我有这个关系:

public function model_info() {
    return $this->hasOne('App\Models\Model', 'id', 'model_id');
}

我如何才能将此关系更改为增变器,因此访问模型名称的旧方法和新方法将同时起作用?我试过withDefault()回调方法没有运气,它返回一个空值:

public function model_info() {
    return $this->hasOne('App\Models\Model', 'id', 'model_id')
                ->withDefault([
                    'name' => $this->attribute->name
                ]);
}

我是否必须在所有控制器和视图中更新代码,或者是否有更简单的方法来进行此操作?

php laravel orm relation
1个回答
0
投票

使用Eloquent mutators

class Estimate {
    public function getNameAttribute(): string {
        return $this->model_info->name;
    }
}

现在您可以按照建议的$estimate->name对其进行访问。这样会加载模型信息关系,您可以自动渴望加载它,我认为如果您经常访问它,那将是最好的方法。

class Estimate {
    $protected $with = ['model_info'];
}
© www.soinside.com 2019 - 2024. All rights reserved.