Skip to content

added MorphToMany with testcases #2640

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

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
147 changes: 141 additions & 6 deletions src/Eloquent/HybridRelations.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
use MongoDB\Laravel\Relations\HasOne;
use MongoDB\Laravel\Relations\MorphMany;
use MongoDB\Laravel\Relations\MorphTo;
use MongoDB\Laravel\Relations\MorphToMany;


use function debug_backtrace;
use function is_subclass_of;
Expand All @@ -41,7 +43,7 @@ trait HybridRelations
public function hasOne($related, $foreignKey = null, $localKey = null)
{
// Check if it is a relation with an original model.
if (! is_subclass_of($related, MongoDBModel::class)) {
if (!is_subclass_of($related, MongoDBModel::class)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Our CS requires that there is a space after exclamation mark. I'll revert this changes with phpcbf before merging.

return parent::hasOne($related, $foreignKey, $localKey);
}

Expand Down Expand Up @@ -70,7 +72,7 @@ public function hasOne($related, $foreignKey = null, $localKey = null)
public function morphOne($related, $name, $type = null, $id = null, $localKey = null)
{
// Check if it is a relation with an original model.
if (! is_subclass_of($related, MongoDBModel::class)) {
if (!is_subclass_of($related, MongoDBModel::class)) {
return parent::morphOne($related, $name, $type, $id, $localKey);
}

Expand All @@ -97,7 +99,7 @@ public function morphOne($related, $name, $type = null, $id = null, $localKey =
public function hasMany($related, $foreignKey = null, $localKey = null)
{
// Check if it is a relation with an original model.
if (! is_subclass_of($related, MongoDBModel::class)) {
if (!is_subclass_of($related, MongoDBModel::class)) {
return parent::hasMany($related, $foreignKey, $localKey);
}

Expand Down Expand Up @@ -126,7 +128,7 @@ public function hasMany($related, $foreignKey = null, $localKey = null)
public function morphMany($related, $name, $type = null, $id = null, $localKey = null)
{
// Check if it is a relation with an original model.
if (! is_subclass_of($related, MongoDBModel::class)) {
if (!is_subclass_of($related, MongoDBModel::class)) {
return parent::morphMany($related, $name, $type, $id, $localKey);
}

Expand Down Expand Up @@ -166,7 +168,7 @@ public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relat
}

// Check if it is a relation with an original model.
if (! is_subclass_of($related, MongoDBModel::class)) {
if (!is_subclass_of($related, MongoDBModel::class)) {
return parent::belongsTo($related, $foreignKey, $ownerKey, $relation);
}

Expand Down Expand Up @@ -278,7 +280,7 @@ public function belongsToMany(
}

// Check if it is a relation with an original model.
if (! is_subclass_of($related, MongoDBModel::class)) {
if (!is_subclass_of($related, MongoDBModel::class)) {
return parent::belongsToMany(
$related,
$collection,
Expand Down Expand Up @@ -323,6 +325,139 @@ public function belongsToMany(
);
}

/**
* Define a many-to-many relationship.
*
* @param string $related
* @param string $collection
* @param string $foreignKey
* @param string $otherKey
* @param string $parentKey
* @param string $relatedKey
* @param string $relation
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
*/
public function morphToMany(
$related,
$name,
$table = null,
$foreignPivotKey = null,
$relatedPivotKey = null,
$parentKey = null,
$relatedKey = null,
$relation = null,
$inverse = false
) {

// Check if it is a relation with an original model.
if (!is_subclass_of($related, \Mongodb\Laravel\Eloquent\Model::class)) {
return parent::MorphToMany(
$related,
$name,
$table,
$foreignPivotKey,
$relatedPivotKey,
$parentKey,
$relatedKey,
$inverse,
);
}

$caller = $this->guessBelongsToManyRelation();

$instance = new $related;

$foreignPivotKey = $foreignPivotKey ?: $name . '_id';

$relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey() . 's';

// Now we're ready to create a new query builder for the related model and
// the relationship instances for this relation. This relation will set
// appropriate query constraints then entirely manage the hydrations.
if (!$table) {
$words = preg_split('/(_)/u', $name, -1, PREG_SPLIT_DELIM_CAPTURE);

$lastWord = array_pop($words);

$table = implode('', $words) . Str::plural($lastWord);
}

return new MorphToMany(
$instance->newQuery(),
$this,
$name,
$table,
$foreignPivotKey,
$relatedPivotKey,
$parentKey ?: $this->getKeyName(),
$relatedKey ?: $instance->getKeyName(),
$caller,
$inverse,
);
}

/**
* Define a polymorphic, inverse many-to-many relationship.
*
* @param string $related
* @param string $name
* @param string|null $table
* @param string|null $foreignPivotKey
* @param string|null $relatedPivotKey
* @param string|null $parentKey
* @param string|null $relatedKey
* @param string|null $relation
* @param bool $inverse
*
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
*/
public function morphedByMany(
$related,
$name,
$table = null,
$foreignPivotKey = null,
$relatedPivotKey = null,
$parentKey = null,
$relatedKey = null,
$inverse = false
) {
$caller = $this->guessBelongsToManyRelation();

// $instance = new $related;
// For the inverse of the polymorphic many-to-many relations, we will change
// the way we determine the foreign and other keys, as it is the opposite
// of the morph-to-many method since we're figuring out these inverses.
$relatedPivotKey = $relatedPivotKey ?: $name . '_id';

$foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey() . 's';

return $this->morphToMany(
$related,
$name,
$table,
$foreignPivotKey,
$relatedPivotKey,
$parentKey,
$relatedKey,
null,
true,
);
}

/**
* Get the relationship name of the belongs to many.
*
* @return string
*/
protected function guessBelongsToManyRelation()
{
if (method_exists($this, 'getBelongsToManyCaller')) {
return $this->getBelongsToManyCaller();
}

return parent::guessBelongsToManyRelation();
}

/** @inheritdoc */
public function newEloquentBuilder($query)
{
Expand Down
189 changes: 189 additions & 0 deletions src/Relations/MorphToMany.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
<?php

declare(strict_types=1);

namespace MongoDB\Laravel\Relations;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class MorphToMany extends BelongsToMany
{
protected $morphType;

protected $morphClass;

/**
* Create a new morph to many relationship instance.
*
* @param Builder $query
* @param Model $parent
* @param string $name
* @param string $table
* @param string $foreignPivotKey
* @param string $relatedPivotKey
* @param string $parentKey
* @param string $relatedKey
* @param string|null $relationName
* @param bool $inverse
*
* @return void
*/
public function __construct(
Builder $query,
Model $parent,
$name,
$table,
$foreignPivotKey,
$relatedPivotKey,
$parentKey,
$relatedKey,
$relationName = null,
protected $inverse = false,
) {
$this->morphType = $name . '_type';
$this->morphClass = $inverse ? $query->getModel()->getMorphClass() : $parent->getMorphClass();

parent::__construct(
$query,
$parent,
$table,
$foreignPivotKey,
$relatedPivotKey,
$parentKey,
$relatedKey,
$relationName,
);
}

/**
* Attach a model to the parent.
*
* @param mixed $id
* @param array $attributes
* @param bool $touch
*
* @return void
*/
public function attach($id, array $attributes = [], $touch = true)
{
if ($id instanceof Model) {
$model = $id;

$id = $model->getKey();

// Attach the new parent id to the related model.
$model->push($this->table, [
$this->foreignPivotKey => $this->parent->getKey(),
$this->morphType => $this->parent instanceof Model ? $this->parent->getMorphClass() : null,
], true);
} else {
if ($id instanceof Collection) {
$id = $id->modelKeys();
}

$query = $this->newRelatedQuery();

$query->whereIn($this->related->getKeyName(), (array) $id);

// Attach the new parent id to the related model.
$query->push($this->table, [
$this->foreignPivotKey => $this->parent->getKey(),
$this->morphType => $this->parent instanceof Model ? $this->parent->getMorphClass() : null,
], true);
}

// Attach the new ids to the parent model.
$this->parent->push($this->relatedPivotKey, (array) $id, true);

if ($touch) {
$this->touchIfTouching();
}
}

/** @inheritdoc */
public function detach($ids = [], $touch = true)
{
if ($ids instanceof Model) {
$ids = (array) $ids->getKey();
}

$query = $this->newRelatedQuery();

// If associated IDs were passed to the method we will only delete those
// associations, otherwise all of the association ties will be broken.
// We'll return the numbers of affected rows when we do the deletes.
$ids = (array) $ids;

// Detach all ids from the parent model.
$this->parent->pull($this->relatedPivotKey, $ids);

// Prepare the query to select all related objects.
if (count($ids) > 0) {
$query->whereIn($this->related->getKeyName(), $ids);
}

// Remove the relation to the parent.
// $query->pull($this->foreignPivotKey, $this->foreignPivotKey, $this->parent->getKey());
$query->pull($this->table, [
$this->foreignPivotKey => $this->parent->getKey(),
$this->morphType => $this->parent instanceof Model ? $this->parent->getMorphClass() : null,
]);

if ($touch) {
$this->touchIfTouching();
}

return count($ids);
}


/**
* Get the foreign key "type" name.
*
* @return string
*/
public function getMorphType()
{
return $this->morphType;
}

/**
* Get the class name of the parent model.
*
* @return string
*/
public function getMorphClass()
{
return $this->morphClass;
}

/**
* Get the indicator for a reverse relationship.
*
* @return bool
*/
public function getInverse()
{
return $this->inverse;
}

/**
* Set the where clause for the relation query.
*
* @return $this
*/
protected function setWhere()
{
$foreign = $this->getForeignKey();

if ($this->getInverse()) {
$this->query->where($foreign, '=', $this->parent->getKey());
} else {
$relatedModels = $this->parent->{$this->relatedPivotKey} ?? [];
$this->query->whereIn($this->relatedKey, $relatedModels);
}

return $this;
}
}
Loading