Search code examples
laraveleloquentrelationshiphas-many-throughhas-many

Laravel hasManythrough?


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.


Solution

  • 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.