joemugen/eloquenty-model

一个 Laravel 类似 Eloquent 的模型类,适用于 Laravel 和其他框架

1.1.0 2022-08-17 14:28 UTC

This package is not auto-updated.

Last update: 2024-09-26 01:25:28 UTC


README

此模型提供了一个 Laravel 类似 Eloquent 的基类,可用于在 Laravel 或其他框架中构建自定义模型。

特性

  • 访问器和修改器
  • 模型到数组/JSON 的转换
  • 数组/JSON 转换中的隐藏属性
  • 受保护属性和可填充属性
  • 将访问器和修改器附加到数组/JSON 转换中
  • 属性类型转换

您可以在 https://laravel.net.cn/docs/eloquent 上了解更多关于这些特性和原始 Eloquent 模型的信息。

安装

使用 Composer 安装

composer require joemugen/eloquenty-model

示例

use JoeMugen\EloquentyModel\Model;

class User extends Model {
    protected $hidden = ['password'];
    protected $guarded = ['password'];
    protected $casts = ['age' => 'integer'];

    public function save()
    {
        return API::post('/items', $this->attributes);
    }

    public function setBirthdayAttribute($value)
    {
        $this->attributes['birthday'] = strtotime($value);
    }

    public function getBirthdayAttribute($value)
    {
        return new DateTime("@$value");
    }

    public function getAgeAttribute($value)
    {
        return $this->birthday->diff(new DateTime('now'))->y;
    }
}

$item = new User(['name' => 'John']);
$item->password = 'secret';

echo $item; // {"name":"John"}