0

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 App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

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

1
  • What is core logic ?if related_id is odd you will relate to ModelB & if it is even then it will relate to ModelC. ritgh? Commented Jun 13, 2024 at 10:59

1 Answer 1

0

I think it is better in this case to use Polymorphic one to many relationship.

Your ModelA Table should contains those columns:

modelable_id - integer
modelable_type - string

Your model will be like that:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ModelA extends Model
{
     public function ModelAable(): MorphTo
    {
        return $this->morphTo();
    }
 }

You can see laravel docs for more details on how to apply it: https://laravel.com/docs/11.x/eloquent-relationships#one-to-many-polymorphic-relations

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.