因此,在我的用户模型中,我有一个函数 fullname 返回用户的全名:
/**
* @return Attribute
*/
public function fullname(): Attribute
{
return new Attribute(
get: fn () => trim($this->firstname . ' ' . $this->lastname),
);
}
它按预期工作,现在我想在我的模型上添加 OpenAPI 注释: 我是这样做的:
class User extends Authenticatable
{
...
protected $appends = [
'fullname'
];
#[OAProperty(type: "string", example: "Jhon")]
private $firstname;
#[OAProperty(type: "string", example: "Doe")]
private $lastname;
/**
* @return Attribute
*/
public function fullname(): Attribute
{
return new Attribute(
get: fn () => trim($this->firstname . ' ' . $this->lastname),
);
}
}
此时该功能不再按预期工作:
$this->firstname and $this->lastname
不再返回空值。
问题:我想保留注释,但也要让函数工作。
注意:如果您通过 eloquent ex 访问您的用户。 ( User::all()->first(); )我们得到了名字和姓氏,但没有得到全名,感谢您的帮助
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
https://github.com/DarkaOnLine/L5-Swagger/issues/157
根据这个问题: 在模型上定义属性会产生很多 eloquent 的问题
我找到了 3 种方法来解决这个问题:
选项 1:您需要进行的重构量最少
保留注释并删除属性定义,例如: 这:
will become 这:
注意:属性或注释必须位于变量或函数之上,否则会产生错误。
选项 2:更干净,但增加了更多工作
将您的开放 API 声明放在其他地方。例如:
选项 3: 这就是我使用的
将您的属性添加到架构声明中 示例:
#[OA\Schema(schema: "IUser", properties: [ new OA\Property(property: "firstname", type: "string", example: "Jhon"), new OA\Property(property: "lastname",type: "string", example: "Doe") ])]