eroslover/laravel-references

Laravel模型之间的引用关系

1.0.5 2019-07-09 11:08 UTC

This package is auto-updated.

Last update: 2024-09-29 05:42:18 UTC


README

Software License

这个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;
}

选择你想要引用照片的模型。例如PersonLocationEvent

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方法接受nullModel或模型的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)。请参阅许可证文件以获取更多信息。