我正在使用 Laravel (Lumen) 创建一个 API,其中的对象包含一个字段,该字段是一个文件的路径。
这些路径在数据库中存储为相对路径,但在将它们返回给用户时,我必须将它们转换为绝对 url。
现在我想知道是否有一种方便的方法可以将非持久字段添加到模型对象中。明明有Mutators但它们会持久保存到数据库中。
我也想过创建一个后中间件,它遍历对象树并转换它找到的每个 path
字段,但这不是一种优雅的方式。
这是我需要的最终转换:
[
{
"id": 1,
"title": "Some title",
"media": [
{
"id": 435,
"path": "relative/path/to/some/file.ext"
},
{
"id": 436,
"path": "relative/path/to/some/file2.ext"
}
]
}
]
收件人:
[
{
"id": 1,
"title": "Some title",
"media": [
{
"id": 435,
"url": "http://example.com/relative/path/to/some/file.ext"
},
{
"id": 436,
"url": "http://example.com/relative/path/to/some/file2.ext"
}
]
}
]
欢迎任何想法。
最佳答案
您可以使用 Laravel accessors ,
来自Docs :
The original value of the column is passed to the accessor, allowing you to manipulate and return the value.
这些不会持久保存在数据库中,但会在您访问它们时进行修改。
例如:
class User extends Model
{
/**
* Get the user's first name.
*
* @param string $value
* @return string
*/
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
}
用法:
$user = App\User::find(1);
$firstName = $user->first_name;
在您的用例中:
在媒体模型中为路径属性定义一个访问器。
public function getPathAttribute($value)
{
return storage_path($value);
}
如果您需要访问具有不同名称(别名)的属性:
public function getAliasAttribute()
{
return storage_path($this->attributes['path']);
}
// $model->alias
关于php - 是否可以向 Laravel 模型添加非持久属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48515546/