0

I have three models creating a many-to-many relationship

ModelA(id)
ModelB(A.id,C.id)
ModelC(id,name)

How to fetch C.name using model A?

Currently model A hasOne model B, and model C hasMany model B. I tried to relate model A and C using hasOnethrough using model B but it gives me null.

1 Answer 1

1
public function myFunction()
{
    return $this->hasOnethrough(ModelC::class, ModelB::class,
        'a_id', 'id', 'id', 'c_id');
}

Based on your question ModelB is your pivot model to handle your relationship.

Normally we use pivot tables for many-to-many relationships, in that case you can use the hasManyThrough method.

You can try the above function in your ModelA model like you asked and will link to modelC through the ModelB

Then you can fetch it like a normal relationship output.

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.