I need to set up conditional belongsTo relationships. Specifically, I have ModelA that can belong to either ModelB or ModelC based on a column value (related_id). For example, if related_id is 1, it should relate to ModelB; if it’s 2, it should relate to ModelC. The relationships are stored in the same field. Here’s a simplified version of what I’m trying to achieve:
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentRelationsBelongsTo;
class ModelA extends Model
{
public function modelB(): BelongsTo
{
return $this->belongsTo(ModelB::class, 'related_id', 'id');
}
public function modelC(): BelongsTo
{
return $this->belongsTo(ModelC::class, 'related_id', 'id');
}
}
I want to be able to load the correct relationship dynamically based on the value of related_id without having to use conditional logic in my repositories or elsewhere. Is there a way to handle this directly within the model?
I tried using where directly in the belongsTo method, but it didn’t work as expected
Jakub Stępień is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.