Laravel Attributes 技术文档
安装指南
系统要求
- PHP:
^8.0
- Laravel Framework:
^9.0
安装步骤
-
使用 Composer 安装包:
composer require milwad/laravel-attributes
-
发布配置文件:
php artisan vendor:publish --provider="Milwad\LaravelAttributes\LaravelAttributesServiceProvider"
-
运行迁移文件:
php artisan migrate
项目使用说明
模型中使用 Trait
在需要使用属性的模型中引入 Attributable
Trait:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Milwad\LaravelAttributes\Traits\Attributable;
class Product extends Model
{
use HasFactory, Attributable;
}
保存单个属性
使用 attachAttribute
方法为模型附加属性:
$product = Product::query()->create([
'name' => 'milwad',
'content' => 'laravel attributes',
]);
$product->attachAttribute('age', '17');
保存多个属性
使用 attachAttributes
方法为模型附加多个属性:
$product = Product::query()->create([
'name' => 'milwad',
'content' => 'text',
]);
$data = [
['title' => 'milwad', 'value' => 'developer'],
['title' => 'milwad2', 'value' => 'developer2'],
// 其他属性...
];
$product->attachAttributes($data);
获取属性
使用 attributes
关系获取模型的属性:
$product = Product::query()->with('attributes')->get();
$product->attributes;
检查属性值是否存在
使用 hasAttributeValue
方法检查模型是否包含某个属性值:
if ($product->hasAttributeValue('17')) {
return 'attribute value';
}
return 'no attribute value';
检查属性标题是否存在
使用 hasAttributeTitle
方法检查模型是否包含某个属性标题:
if ($product->hasAttributeTitle('milwad')) {
return 'attribute title';
}
return 'no attribute title';
删除所有属性
使用 deleteAllAttribute
方法删除模型的所有属性:
$product->deleteAllAttribute();
删除特定属性
使用 deleteAttribute
方法删除模型的特定属性:
$product->deleteAttribute('title', 'value');
按标题删除特定属性
使用 deleteAttributeByTitle
方法按标题删除特定属性:
$product->deleteAttributeByTitle('title');
按值删除特定属性
使用 deleteAttributeByValue
方法按值删除特定属性:
$product->deleteAttributeByValue('value');
项目API使用文档
属性相关API
attachAttribute(string $title, string $value)
: 为模型附加单个属性。attachAttributes(array $data)
: 为模型附加多个属性。attributes
: 获取模型的属性关系。hasAttributeValue(string $value)
: 检查模型是否包含某个属性值。hasAttributeTitle(string $title)
: 检查模型是否包含某个属性标题。deleteAllAttribute()
: 删除模型的所有属性。deleteAttribute(string $title, string $value)
: 删除模型的特定属性。deleteAttributeByTitle(string $title)
: 按标题删除特定属性。deleteAttributeByValue(string $value)
: 按值删除特定属性。
项目安装方式
使用 Composer 安装
composer require milwad/laravel-attributes
发布配置文件
php artisan vendor:publish --provider="Milwad\LaravelAttributes\LaravelAttributesServiceProvider"
运行迁移文件
php artisan migrate
通过以上步骤,您可以成功安装并使用 Laravel Attributes 包来简化 Laravel 项目中的属性管理。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考