php Laravel雄辩的模型与 Swagger openApi注解问题

5jvtdoz2  于 2022-12-10  发布在  PHP
关注(0)|答案(1)|浏览(109)

因此,在我的用户模型中,我有一个函数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'
    ];

    #[OA\Property(type: "string", example: "Jhon")] 
    private $firstname; 

    #[OA\Property(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

不再返回空值。
问题:我想保留注解,但同时让函数工作。
注意:如果你通过雄辩的方式访问你的用户,例如(User::all()-〉first();)我们会同时取得名字和姓氏,但不会取得全名,感谢您的协助

jm2pwxwz

jm2pwxwz1#

https://github.com/DarkaOnLine/L5-Swagger/issues/157
根据这一问题:在模型上定义属性会产生许多问题,
我找到了3种方法来解决这个问题:

**选项1:**只需执行最少的重构

保留注解并删除属性定义,例如:这是:

#[OA\Property(type: "string", example: "Jhon")] 
private $firstname; 

#[OA\Property(type: "string", example: "Doe")] 
private $lastname;

会变成这样:

#[OA\Property(property: "firstname", type: "string", example: "Jhon")] 
#[OA\Property(property: "lastname",type: "string", example: "Doe")]

注意:属性或注解必须在变量或函数之上,否则将生成错误。

**选项2:**更干净,但增加更多工作

把你开放API声明放到别的地方。2例如:

  • 响应资源:https://github.com/DarkaOnLine/L5-Swagger/issues/157#issuecomment-406204764
  • 创建一个新目录(virtual),并将所有OpenAPI注解放在其中:https://github.com/DarkaOnLine/L5-Swagger/issues/157#issuecomment-655865772
    **选项3:**这是我使用的

将属性添加到模式声明示例中:

#[OA\Schema(schema="IUser", properties: [
    new OA\Property(property: "firstname", type: "string", example: "Jhon"),
    new OA\Property(property: "lastname",type: "string", example: "Doe")
])]

相关问题