1

I am building an admin panel using Laravel nova. I have an Items table, that has a belongsToMany to itself, using (of course) a pivot table.

This in itself is working, but when I specify that item A is related to item B, the inverse of that relation is not stored, so that results in not being found on item B.

I need it to, because the relationship is symmetrical, meaning that if A relates to B, B also relates to A.

What would be the best way to store and retrieve the relation?

This is my current code that defines the relation, and that works one way.

class Item extends Model
{
    public function related(): BelongsToMany
    {
        return $this->belongsToMany(Item::class, 'item_related', 'item_id', 'related_id');
    }
}

So: imagine I have a table with the items A, B and C, and the relations are defined as such in the pivot table

item_id - related_id
A       - B
A       - C
B       - C

So basically, when I do B->related, I want it to return [A, C]. Now it will only return C, and C does not have any related items at all

There are two possible solutions here, one being to insert the inverse relation as well, resulting in

item_id - related_id
A       - B
B       - A
A       - C
C       - A
B       - C
C       - B

This will yield the correct results, but how to automatically force laravel to save the inverted relation as well, and making sure that deletions etc are correctly done?

The other option would be is 'merging' two related belongsToMany calls.

class Item extends Model
{
    public function related(): BelongsToMany
    {
        // return merged $this->relatedFrom and $this->relatedTo
    }

    public function relatedFrom(): BelongsToMany
    {
        return $this->belongsToMany(Item::class, 'item_related', 'related_id', 'item_id');
    }

    public function relatedTo(): BelongsToMany
    {
        return $this->belongsToMany(Item::class, 'item_related', 'item_id', 'related_id');
    }

}

This would also cause all kind of problems.

So what would be a good approach here?

2
  • I added the code that I currently use to define the relation. It's not much that's relevant here.
    – jberculo
    Commented Sep 7, 2020 at 16:03
  • I added the way I solved this as an answer, other approaches are of course welcome :)
    – jberculo
    Commented Sep 8, 2020 at 10:30

2 Answers 2

3

I opted for the method of adding the reverse relation to the pivot table, using an observer and a Pivot model

Normally, a model is not made when having a belongsToMany relation. In this case I needed one, so I manually created one.

The Pivot model, note it extending Pivot instead of Model, the observer being added in the boot method, and the $timestamps which I set to false:

namespace App\Models;

use App\Observers\RelationObserver;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\Pivot;

class ItemRelated extends Pivot
{

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'item_related';

    public $timestamps = false;

    public static function boot(): void
    {
        parent::boot();
        parent::observe(new RelationObserver);
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'item_id',
        'related_id',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'item_id' => 'integer',
        'related_id' => 'integer',
    ];

}

The observer only needs a created and deleted method, inserting and deleting the reverse relation after the other is inserted or deleted respectively:

namespace App\Observers;

use App\Models\ItemRelated;

class RelationObserver
{
    public function created(ItemRelated $itemRelated): void
    {
        if (ItemRelated::where([
            ['item_id', '=', $itemRelated->related_id],
            ['related_id', '=', $itemRelated->item_id],
        ])->doesntExist()) {
            $itemRelatedReverse = new ItemRelated();
            $itemRelatedReverse->item_id = $itemRelated->related_id;
            $itemRelatedReverse->related_id = $itemRelated->item_id;
            $itemRelatedReverse->save();
        }
    }

    public function deleted(ItemRelated $itemRelated): void
    {
        ItemRelated::where([
            ['item_id', '=', $itemRelated->related_id],
            ['related_id', '=', $itemRelated->item_id],
        ])->delete();
    }
}

At last I need to tell the relation on the Item table to use the pivot table, by chaining the using method:

public function related(): BelongsToMany
{
    return $this->belongsToMany(Item::class, 'item_related', 'item_id', 'related_id')
        ->using(ItemRelated::class);
}
1

An alternative answer to your question would be to add a new method in your Item model.

Given that you already figured out the two-way relationship:

public function relatedFrom(): BelongsToMany
{
    return $this->belongsToMany(Item::class, 'item_related', 'related_id', 'item_id');
}

public function relatedTo(): BelongsToMany
{
    return $this->belongsToMany(Item::class, 'item_related', 'item_id', 'related_id');
}

You could merge them to return collection:

public function itemRelations(): Collection
{
    return $this->relatedFrom()->get()
                ->merge($this->relatedTo()->get())
                ->unique('id');
}
1
  • Nice, far more simple
    – jberculo
    Commented Jul 18, 2023 at 14:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.