eroslover / laravel-references
Laravel模型之间的引用关系
1.0.5
2019-07-09 11:08 UTC
Requires
- php: >=7.0.0
- illuminate/contracts: ~5.1
- illuminate/database: ~5.1
- illuminate/http: ~5.1
- illuminate/support: ~5.1
- laravel/framework: ~5.1
Requires (Dev)
- phpunit/phpunit: ~5.7
README
这个Laravel包提供了一种快速简单的方式,在任意Eloquent模型之间建立引用关系。
以下是一些简短的示例,展示你可以做什么
// photo of some persons $photo = Photo::find(1); // persons you want to refer with this photo $person1 = Person::find(1); $person2 = Person::find(2); // making a reference $photo->ref($person1); $photo->ref($person2); // you are able to refer a collection of persons $persons = Person::find([1, 2]); $photo->ref($persons);
安装
你可以通过Composer安装此包
$ composer require eroslover/laravel-references
服务提供器将被自动注册。或者,你也可以手动在config/app.php文件中添加服务提供器
'providers' => [ ... Eroslover\References\ReferencesServiceProvider::class, ];
现在使用以下命令发布迁移和配置
php artisan vendor:publish --provider="Eroslover\References\ReferencesServiceProvider"
这是发布配置文件的详细内容
return [ /* * Name of the database table that will store model references. */ 'table_name' => 'references' ];
在这里,你可以更改将要用于引用的表名。
迁移发布后,你可以通过运行迁移来创建引用表
php artisan migrate
用法
选择你想要添加引用的模型。例如,在上述示例中,我会选择Photo
。这个类应该实现ReferencesInterface
接口并导入References
特质。
namespace App; use Eroslover\References\Traits\References; use Eroslover\References\Interfaces\ReferenceInterface; use Illuminate\Database\Eloquent\Model; class Photo extends Model implements ReferenceInterface { use References; }
选择你想要引用照片的模型。例如Person
、Location
和Event
。
namespace App; use Illuminate\Database\Eloquent\Model; class Person extends Model {} class Location extends Model {} class Event extends Model {}
建立引用
ref
方法接受Model
或模型的Collection
来将数据放入引用表中
$photo = Photo::find(1); $location = Location::find(3); $persons = Person::whereLocation($location->id)->get(); $event = Event::first(); $photo->ref($location); $photo->ref($persons); $photo->ref($event);
移除引用
unref
方法接受Model
或模型的Collection
来从引用表中移除它们
$photo->unref($location);
同步引用
syncRefs
方法接受null
、Model
或模型的Collection
来将数据或从引用表中移除数据。不在给定集合中的任何模型都将从引用表中移除。因此,当此操作完成时,只有给定集合中的模型将在所选模型的引用表中存在
$photo->syncRefs($referencable);
检索引用
loadReferences
方法返回引用模型的集合。接受布尔参数$grouped
。默认情况下,方法返回映射的集合,其中键是命名空间,值是一组实体。如果你需要获取引用实体的集合,你需要将false
作为参数传递给方法
$photo->loadReferences(); Output: ReferenceCollection {#1715 ▼ #items: array:3 [▼ "App\Modules\Location" => Collection {#1730 ▼ #items: array:1 [▼ 0 => Location {#1731 ▶} ] } "App\Modules\Person" => Collection {#1733 ▼ #items: array:2 [▼ 0 => Person {#1734 ▶} 1 => Person {#1735 ▶} ] } "App\Modules\Event" => Collection {#1737 ▼ #items: array:1 [▼ 0 => Event {#1738 ▶} ] } ] }
$photo->loadReferences(false); Output: Collection {#1716 ▼ #items: array:4 [▼ 0 => Location {#1731 ▶} 1 => Person {#1732 ▶} 2 => Person {#1734 ▶} 3 => Event {#1735 ▶} ] }
测试
你可以使用以下命令运行测试
$ vendor/bin/phpunit
许可证
MIT许可证(MIT)。请参阅许可证文件以获取更多信息。