statamic-rad-pack / runway

Eloquently manage your database models in Statamic.
https://statamic.com/addons/rad-pack/runway
MIT License
112 stars 47 forks source link

STI broken by reference-passing PR #491

Closed caseydwyer closed 4 months ago

caseydwyer commented 4 months ago

Description

When using an app that leverages STI (single-table inheritance), the new passing of reference introduced in #486 will break relationship fields. Tighten's Parental package is a good reference for this concept.

I imagine this is bit of an edge case, but there's also a pretty quick and easy fix—just wanted to share that by dropping (and closing) this issue, in case anyone else runs into this and comes looking for help.

The Problem

This issue will apply if you have at least one model that leverages both HasRunwayResource and HasChildren (using the aforementioned Parental methods for this example). Say you have a Post model that belongs to a User model, but that User is wired up as a parent with multiple "child" models—say Admin and Editor. Here's what happens as of v6.7.1:

  1. Your parent has a runwayResource method, from the HasRunwayResource trait
  2. That method attempts to findResourceByModel (on the Runway class)
  3. That method call uses $this as the parameter, which is the child and not the parent
  4. Since you've probably wired the parent (and not the child) as a resource, Runway doesn't look for/find the right model

The Solution

On your parent model, simply overwrite the runwayResource method from the HasRunwayResource trait. Here's the definition from the trait, for reference:

public function runwayResource(): Resource
{
    return Runway::findResourceByModel($this);
}

So in your parent model, you can skip the $model-based lookup and use the string-based findResource method instead. Just pass it the resource name directly, and you should be set:

public function runwayResource(): ?Resource
{
    return Runway::findResource('user');
}

This ensures that all children, which should be extending this parent class, will use the correct resource (ie, the one that's associated with your parent model).

caseydwyer commented 4 months ago

Hope that's helpful for anyone else who runs into a similar issue!

duncanmcclean commented 4 months ago

Glad you managed to find a workaround. Like you say, it's a bit of an edge case 😅

caseydwyer commented 4 months ago

Haha, very much so—just thought I'd mention it here, in case somebody else stumbles onto a similar issue (ie, probably me, in about six months or so 😂). Thanks Duncan!