Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TaggedToMany Relationship #514

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/HasTags.php
Original file line number Diff line number Diff line change
Expand Up @@ -302,4 +302,17 @@ protected function syncTagIds($ids, string | null $type = null, $detaching = tru
$this->tags()->touchIfTouching();
}
}

/**
* Return a new TaggedToMany relationship
*
* @param string $related
* @param string|null $type
*
* @return \Spatie\Tags\TaggedToMany
*/
public function taggedToMany(string $related, string|null $type = null): TaggedToMany
{
return new TaggedToMany($this, $related, $type);
}
}
36 changes: 20 additions & 16 deletions src/Tag.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,15 @@ public function scopeContaining(Builder $query, string $name, $locale = null): B
{
$locale = $locale ?? static::getLocale();

return $query->whereRaw('lower(' . $this->getQuery()->getGrammar()->wrap('name->' . $locale) . ') like ?', ['%' . mb_strtolower($name) . '%']);
return $query->whereRaw('lower('.$this->getQuery()->getGrammar()->wrap('name->'.$locale).') like ?',
['%'.mb_strtolower($name).'%']);
}

public static function findOrCreate(
string | array | ArrayAccess $values,
string | null $type = null,
string | null $locale = null,
): Collection | Tag | static {
string|array|ArrayAccess $values,
string|null $type = null,
string|null $locale = null,
): Collection|Tag|static {
$tags = collect($values)->map(function ($value) use ($type, $locale) {
if ($value instanceof self) {
return $value;
Expand All @@ -70,22 +71,25 @@ public static function findFromString(string $name, string $type = null, string
$locale = $locale ?? static::getLocale();

return static::query()
->where('type', $type)
->where(function ($query) use ($name, $locale) {
$query->where("name->{$locale}", $name)
->orWhere("slug->{$locale}", $name);
})
->first();
->where('type', $type)
->where(function ($query) use ($name, $locale) {
$query->where("name->{$locale}", $name)
->orWhere("slug->{$locale}", $name)
;
})
->first()
;
}

public static function findFromStringOfAnyType(string $name, string $locale = null)
{
$locale = $locale ?? static::getLocale();

return static::query()
->where("name->{$locale}", $name)
->orWhere("slug->{$locale}", $name)
->get();
->where("name->{$locale}", $name)
->orWhere("slug->{$locale}", $name)
->get()
;
}

public static function findOrCreateFromString(string $name, string $type = null, string $locale = null)
Expand All @@ -94,7 +98,7 @@ public static function findOrCreateFromString(string $name, string $type = null,

$tag = static::findFromString($name, $type, $locale);

if (! $tag) {
if (!$tag) {
$tag = static::create([
'name' => [$locale => $name],
'type' => $type,
Expand All @@ -111,7 +115,7 @@ public static function getTypes(): Collection

public function setAttribute($key, $value)
{
if (in_array($key, $this->translatable) && ! is_array($value)) {
if (in_array($key, $this->translatable) && !is_array($value)) {
return $this->setTranslation($key, static::getLocale(), $value);
}

Expand Down
115 changes: 115 additions & 0 deletions src/TaggedToMany.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
<?php

namespace Spatie\Tags;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\JoinClause;

class TaggedToMany extends Relation
{

public function __construct(Model $parent, string $related, public string|null $type = null)
{
$instance = new $related;

parent::__construct($instance->query(), $parent);
}

/**
* @inheritDoc
*/
#[\Override] public function addConstraints()
{
$this->query->select($this->related->getTable().".*")
->join("taggables as taggables_related", "taggables_related.taggable_id",
$this->related->getTable().".".$this->related->getKeyName())
->join("taggables as taggables_parent", "taggables_parent.tag_id", "taggables_related.tag_id")
->join("tags", "taggables_parent.tag_id", "tags.id")
->where("taggables_parent.taggable_type", get_class($this->parent))
->where("taggables_related.taggable_type", get_class($this->related))
->where("tags.type", $this->type)
;

if ($this->parent->getKey()) {
$this->query->where("taggables_parent.taggable_id", $this->parent->getKey());
}
}

/**
* @inheritDoc
*/
#[\Override]
public function addEagerConstraints(array $models)
{
$this->query->select([$this->related->getTable().".*", "taggables_parent.taggable_id"])
->whereIn("taggables_parent.taggable_id", array_map(fn(Model $model) => $model->getKey(), $models))
;
}

/**
* @inheritDoc
*/
#[\Override] public function initRelation(array $models, $relation)
{
foreach ($models as $model) {
$model->setRelation(
$relation,
$this->related->newCollection()
);
}

return $models;
}

/**
* @inheritDoc
*/
#[\Override] public function match($models, Collection $results, $relation)
{
if ($results->isEmpty()) {
return $models ?? [];
}

foreach ($models as $model) {
$model->setRelation(
$relation,
$results->unique()->filter(function (Model $related) use ($model) {
return $related->taggable_id === $model->id;
})->values()
);
}

return $models;
}

/**
* @inheritDoc
*/
#[\Override] public function getResults()
{
return $this->query->get();
}

/**
* @inheritDoc
*/
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
{
$query->join("taggables as taggables_related", "taggables_related.taggable_id",
$this->related->getTable().".".$this->related->getKeyName())
->join("taggables as taggables_parent", function (JoinClause $join) {
$join->on("taggables_parent.tag_id", "taggables_related.tag_id")
->on("taggables_parent.taggable_id",
$this->parent->getTable().".".$this->parent->getKeyName())
;
})
->join("tags", "taggables_parent.tag_id", "tags.id")
->where("tags.type", $this->type)
;

return $query;
}
}
94 changes: 94 additions & 0 deletions tests/TaggedToManyTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php

use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Spatie\Tags\Tag;
use Spatie\Tags\Test\TestClasses\TestAnotherModel;
use Spatie\Tags\Test\TestClasses\TestModel;

beforeEach(function () {
$this->testParentModel = TestModel::create(['name' => 'parent']);
$this->testRelatedModel_1 = TestAnotherModel::create(['name' => 'model 1']);
$this->testRelatedModel_2 = TestAnotherModel::create(['name' => 'model 2']);
});


it('should return other model with same tags', function () {
$testTag = "Test Tag";

$this->testParentModel->attachTag($testTag);
$this->testRelatedModel_2->attachTag($testTag);

$res = $this->testParentModel->anotherModels;
$this->assertCount(1, $res);
$this->assertEquals($this->testRelatedModel_2->id, $res->first()->id);
});

it('should not return other models without same tags', function () {
$testTag = "Test Tag";
$testOtherTag = "Other Tag";

$this->testParentModel->attachTag($testTag);
$this->testRelatedModel_2->attachTag($testOtherTag);

$res = $this->testParentModel->anotherModels;
$this->assertCount(0, $res);
});

it('should return other model with same tags and of same type', function () {
$testTag = "Test Tag";

$this->testParentModel->attachTag($testTag, "test-type");
$this->testRelatedModel_2->attachTag($testTag, "test-type");

$res = $this->testParentModel->anotherModelsOfType;
$this->assertCount(1, $res);
$this->assertEquals($this->testRelatedModel_2->id, $res->first()->id);
});

it('should not return other model with same tags and of different type', function () {
$testTag = "Test Tag";

$this->testParentModel->attachTag($testTag, "test-type");
$this->testRelatedModel_2->attachTag($testTag, "other-type");

$res = $this->testParentModel->anotherModelsOfType;
$this->assertCount(0, $res);
});

it('should query existence ok without specifying type, expecting 1', function () {
$testTag = "Test Tag";

$this->testParentModel->attachTag($testTag);
$this->testRelatedModel_2->attachTag($testTag);

$res = TestModel::whereHas("anotherModels")->get();
$this->assertCount(1, $res);
});

it('should query existence ok without specifying type, expecting 0', function () {
$testTag = "Test Tag";

$this->testParentModel->attachTag($testTag);

$res = TestModel::whereHas("anotherModels")->get();
$this->assertCount(0, $res);
});

it('should query existence ok while specifying type, expecting 1', function () {
$testTag = "Test Tag";

$this->testParentModel->attachTag($testTag, "test-type");
$this->testRelatedModel_2->attachTag($testTag, "test-type");

$res = TestModel::whereHas("anotherModelsOfType")->get();
$this->assertCount(1, $res);
});

it('should query existence ok while specifying type, expecting 0', function () {
$testTag = "Test Tag";

$this->testParentModel->attachTag($testTag, "test-type");

$res = TestModel::whereHas("anotherModels")->get();
$this->assertCount(0, $res);
});
11 changes: 11 additions & 0 deletions tests/TestClasses/TestModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Database\Eloquent\Model;
use Spatie\Tags\HasTags;
use Spatie\Tags\TaggedToMany;

class TestModel extends Model
{
Expand All @@ -14,4 +15,14 @@ class TestModel extends Model
protected $guarded = [];

public $timestamps = false;

public function anotherModels(): TaggedToMany
{
return $this->taggedToMany(TestAnotherModel::class);
}

public function anotherModelsOfType(): TaggedToMany
{
return $this->taggedToMany(TestAnotherModel::class, "test-type");
}
}
Loading