Getting the inverse of a Many-relation
Hey there,
I'm using a MorphToMany relation and when calling a method on the morphed model, I'm looking for a way to get the single model that called me inside that method. To better understand, here's an example of what I'm doing:
Table structure
ticket_provider_a
id - integer
column_special_to_a
ticket_provider_b
id - integer
column_special_to_b
another_column_special_to_b
ticket_pools
id - integer
name - string
ticket_provider_id - integer
ticket_provider_type - string
The models:
class TicketPool extends Model
{
public function ticketProvider(): MorphTo
{
return $this->morphTo(__FUNCTION__, 'ticket_provider_type', 'ticket_provider_id');
}
}
class TicketProviderA extends Model // Same for TicketProviderB
{
public function ticketPools(): MorphMany
{
return $this->morphMany(TicketPool::class, 'ticketPools', 'ticket_provider_type', 'ticket_provider_id');
}
}
So a TicketProvider is basically some kind of "dynamic config" that admins can manage via a Nova backend and assign to a TicketPool. Hence a TicketProvider can be used with multiple TicketPools, but a TicketPool can only have a single TicketProvider. This all works great so far.
Now imagine a method in one of the providers that gets called from an instance of a TicketPool:
class TicketPool extends Model
{
private function doMagic(): void
{
// $ticketProvider is available and can be called. No issue here:
$this->ticketProvider->doSomething();
}
}
class TicketProviderA extends Model
{
public function doSomething(): void
{
// We now want to know which TicketPool called us, to e.g. get its name and do more actions with it.
// This will of course not work, as it's undefined:
$this->ticketPool->name;
// This will work, but has all TicketPools that this TicketProvider is assigned to and of course [0] is basically random. So this also doesn't give us what we need:
$this->ticketPools[0]->name;
}
}
But what is the way now to actually get the "calling model"? I tried looking through a bit, and found things like $this->ticketPools()->getRelated(), but that is simply an empty model...
Sure, I can pass the TicketPool as a parameter to doSomething(), but it feels like there must be an Eloquent way to get it :)
Thanks already for the help and greetings,
Andy!
Please or to participate in this conversation.