gmory / laranotes
将备注附加到您模型的包。
Requires
Requires (Dev)
- orchestra/database: ^3.4
- orchestra/testbench: ^3.4
- phpunit/phpunit: ^5.7
This package is not auto-updated.
Last update: 2024-09-22 12:55:16 UTC
README
一个laravel包,允许您将备注附加到您选择的任何模型。当您想向任何模型添加信息片段时,这尤其有用。
使用场景
一些使用场景包括
- 为具有与异常相关的可读消息的模型添加备注。
- 记录用户的登录/注销时间。
- 记录最后编辑文章的用户。
安装
使用Composer安装此包。
- 您可以通过运行以下命令完成此操作
composer require gmory/laranotes
- 将服务提供者添加到您的
config/app.php
文件
'providers' => [
...
Gmory\Laranotes\LaranotesServiceProvider::class,
];
- 将外观添加到您的
config/app.php
文件
'Laranote' => Gmory\Laranotes\LaranotesFacade::class,
用法
使用 NotesTrait 设置关系
首先将 NotesTrait
放在您希望附加备注的每个模型上。这将赋予这些模型适当的关联以访问它们的备注。
添加备注
要添加备注,请使用 attach($model)
指定您想要附加备注的模型,然后使用 note($content, [$unique])
方法。
Laranote::attach($user)->note('This user is great!');
您可以通过在 note()
方法的第二个参数中传递 true 来指定仅添加唯一的备注(确保不添加重复的相同备注)。
Laranote::attach($user)->note('If this note already exists, do not attach it again.', true);
您可以使用 regarding($model)
将备注视为次要模型。当您想将备注附加到特定模型,但又想了解备注所引用的内容时,这很有用。
Laranote::attach($user)->regarding($post)->note($user->name . ' edited this post.');
删除备注
您可以通过使用 deleteOld([$attachedToModel], [$regardingModel], [$onlyThoseBelongingToBoth], [$content])
创建新备注时删除与模型关联的所有旧备注。
为了使此函数删除任何备注,您必须包含 $attachedToModel
或 $regardingModel
。
您可以通过指定您只想删除同时具有 $attachedTo
模型和 $regardingModel
的备注,以及/或指定您要删除的备注的确切 $content
,来进一步扩展删除功能。
删除附加到 $user
的所有备注
Laranote::deleteOld($user);
删除所有关于 $post
的备注
Laranote::deleteOld(null, $post));
删除附加到 $user
并关于 $post
的所有备注
Laranote::deleteOld($user, $post));
仅删除同时附加到 $user
并关于 $post
的备注
Laranote::deleteOld($user, $post, true));
仅删除同时附加到 $user
并关于 $post
且内容为 'User authored a new post' 的备注
Laranote::deleteOld($user, $post, true, 'User authored a new post'));
检索备注
要从特定模型检索备注,您可以调用 NotesTrait
授予的 notes()
关系。
$user->notes
要检索任何关于特定模型的备注,您可以调用 regardedBy()
关系,该关系由 NotesTrait
授予。
$user->regardedBy
备注属性
要返回备注的内容,请调用 content
属性
$note->content
要返回备注附加到的模型,请使用 noting
关系
$note->noting
要返回备注所关注的模型,请使用 regarding
关系
$note->regarding
许可
MIT