staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

BelongToMany to belongsTo Relationship #37

Closed nitish1986 closed 5 years ago

nitish1986 commented 5 years ago

Hello,

I'm having following models and table name:

Tags: table name (project_tags)

id
name

which is related to TechnicalDescription model with many to many relationship:

TechnicalDescription: table name(project_technical_detail)

id
project_id
description

Many to many relation holds on table (technical_detail_tag_relation):

id
technical_detail_id
tag_id

And finally I have Project Model table name(projects)

id
name

So I have Tags -> belongsToMany -> TechnicalDescription -> belongsTo -> Project

I tried doing:

public function projects()
{
    return $this->hasManyDeep(
        Project::class,
        ['technical_detail_tag_relation', TechnicalDescription::class],
        [null, null, 'id'],
        [null, null, 'project_id']
    );
}

But it throws error:

Column not found: 1054 Unknown column 'technical_detail_tag_relation.technical_description_id' in 'on clause'

Can you help me out with it, I tried replacing technical_description_id almost every null place where I defined this relationship, but no luck.

I'm trying to learn about your package, but little confused with this kind of relationships.

Thanks.

nitish1986 commented 5 years ago

I tried fixing this:

public function projects()
{
    return $this->hasManyDeep(
        Project::class,
        ['technical_detail_tag_relation', TechnicalDescription::class],
        ['tag_id', 'id', 'id'],
        ['id', 'technical_detail_id', 'id']
    );
}

I think it is working. Just need confirmation about it. Thanks.

staudenmeir commented 5 years ago

You are missing the project_id column:

public function projects()
{
    return $this->hasManyDeep(
        Project::class,
        ['technical_detail_tag_relation', TechnicalDescription::class],
        ['tag_id', 'id', 'id'],
        ['id', 'technical_detail_id', 'project_id']
    );
}