beyondcode/laravel-er-diagram-generator

Pivot table on ManyToMany relationships

Opened this issue · 1 comments

First Thing First... Great Package! 💯

Now about issue: When you have ManyToMany relationship (via belongsToMany) and try to generate diagram, it will include pivot table in diagram, but without proper naming. It will be called 'Pivot'.

For Example: below I have included 2 classes that are connected via M:M relationship and they both have pivot table name (buyer_seller) included in their relationship but on the diagram it still shows table as 'Pivot'.

  • Classes:
    •  class Buyer extends Model
       {
           public function buyer()
           {
               return $this->belongsToMany(Seller::class, 'buyer_seller');
           }
       }
    •   class Seller extends Model
        {
            public function buyer()
            {
                return $this->belongsToMany(Buyer::class, 'buyer_seller');
            }
        }
  • Diagram:
    Screenshot from 2020-11-23 01-52-11

P.S. I don't know if it's my fault or not, but as far as I have read documentation there is nothing written about this exact case. So it would be nice to have feature to enable pivot table naming in diagram.

The offending line is https://github.com/beyondcode/laravel-er-diagram-generator/blob/master/src/GraphBuilder.php#L173 as the $label variable in this instance is what produces the word "Pivot".

The variable $pivotTable is what we're both looking for and I've patched in the following snippet right before the line I linked as:

if ($label == "Pivot") {
    $label = studly_case($pivotTable);
}

This is not 100% ideal because it removes the underscores but title case doesn't work for my schema either because the database uses tables like addressTypes and I want to preserve the word boundaries.

I'm not keen on managing the fork long term but I also don't know a good way to turn this into a general feature. A label of addresses_addressTypes (the value of variable $pivotTable) in a sea of Addresses or Users models looks out of place.

Now that I think about it, I bet if we both used an explicit Pivot model class perhaps this wouldn't be a concern? The line $label = (new \ReflectionClass($pivotClass))->getShortName(); is looking for a class that by default is Pivot until you substitute with a custom class. In later versions of Laravel there's https://laravel.com/docs/8.x/eloquent-relationships#customizing-the-pivot-attribute-name that may change the name but what I'm talking about is more like https://laravel.com/docs/8.x/eloquent-relationships#defining-custom-intermediate-table-models. I'm not really in a place to take either approach but I'm willing to bet one or the other would address the problem without having to change anything in this package.