Php 是否可以向Laravel模型添加非持久性属性?
我正在使用Laravel(Lumen)创建一个API,其中的对象包含一个字段,该字段是文件的路径。Php 是否可以向Laravel模型添加非持久性属性?,php,laravel,lumen,laravel-eloquent,Php,Laravel,Lumen,Laravel Eloquent,我正在使用Laravel(Lumen)创建一个API,其中的对象包含一个字段,该字段是文件的路径。 这些路径作为相对路径存储在数据库中,但在将它们返回给用户时,我必须将它们转换为绝对URL 现在我想知道是否有一种方便的方法向模型对象添加一个非持久性字段。显然有,但是它们被持久化到数据库中 我还想过创建一个after中间件,它遍历对象树并转换它找到的每个路径字段,但这不是一种优雅的方式 以下是我需要的最后一个转换: [ { "id": 1, "title": "Some tit
这些路径作为相对路径存储在数据库中,但在将它们返回给用户时,我必须将它们转换为绝对URL 现在我想知道是否有一种方便的方法向模型对象添加一个非持久性字段。显然有,但是它们被持久化到数据库中 我还想过创建一个after中间件,它遍历对象树并转换它找到的每个
路径
字段,但这不是一种优雅的方式
以下是我需要的最后一个转换:
[
{
"id": 1,
"title": "Some title",
"media": [
{
"id": 435,
"path": "relative/path/to/some/file.ext"
},
{
"id": 436,
"path": "relative/path/to/some/file2.ext"
}
]
}
]
致:
欢迎任何想法。您可以使用
来自:
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 getAliasAttribute()
{
return storage_path($this->attributes['path']);
}
// $model->alias
列的原始值传递给访问器,允许
您需要操作并返回值
这些文件不会持久保存在数据库中,而是在您访问它们时进行修改
例如:
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 getAliasAttribute()
{
return storage_path($this->attributes['path']);
}
// $model->alias
用法:
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 getAliasAttribute()
{
return storage_path($this->attributes['path']);
}
// $model->alias
在您的用例中:
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 getAliasAttribute()
{
return storage_path($this->attributes['path']);
}
// $model->alias
在媒体模型中为路径属性定义访问器
public function getPathAttribute($value)
{
return storage_path($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 getAliasAttribute()
{
return storage_path($this->attributes['path']);
}
// $model->alias
正如@Sapnesh Naik所说,你需要的是一个简单的如下:
public function getPathAttribute($value)
{
$url = config('relative_url') or env('PATH') or $sthElse;
return $url.$this->attributes['path'];
}
太好了,我没有仔细阅读文档,得1分。谢谢,伙计。@HamedMomeni也请查看更新后的答案。我已经添加了一个与您的用例相关的示例。再次感谢,但是有办法更改字段名称本身吗?@HamedMomeni是的,您可以。请看我的最新答案