laravel-shift / blueprint

A code generation tool for Laravel developers.
MIT License
2.82k stars 270 forks source link

Infer `belongsTo` relationships #652

Closed jasonmccreary closed 9 months ago

jasonmccreary commented 9 months ago

After watching Blueprint in action on a Laracast Series, I realized a use case that could be optimized. Blueprint is all about conventions and rapid development, but this video demonstrated some confusion on when to define model columns as well as relationships. Particularly in the case of belongsTo.

Consider the following draft file:

models:
  Conference:
    name: string
    venue_id: unsigned bigInteger
    relationships:
      belongsTo: Venue, Region

In this case a user has defined what they believe to be a foreign key column, but also the belongsTo relationship to Venue. While there are a few ways you may write this, ideally you would do one or the other. Personally, I would not define a belongsTo relationship as simply defining the column is faster (less to type).

For example:

models:
  Conference:
    name: string
    venue_id: id
    region_id: id

However, with this PR, you may also write the following and the foreign key columns will be inferred:

models:
  Conference:
    name: string
    relationships:
      belongsTo: Venue, Region

As a bonus, if you were to write the original draft file, Blueprint will assume the venue_id is meant to be a data type of id.


As a development note to myself and future contributors, these types of adjustments should be done in the lexer. Doing these kinds of things higher up avoid having to do it in several of the underlying generators.