staudenmeir / belongs-to-through

Laravel Eloquent BelongsToThrough relationships
MIT License
1.15k stars 88 forks source link

LocalKey being ignored #33

Closed Eyewash01 closed 5 years ago

Eyewash01 commented 5 years ago

On the Znck\Eloquent\Relations\BelongsToThrough constructor, it allows you to specify a local key, however this appears to be being completely ignored.

staudenmeir commented 5 years ago

This is not a mistake. When I took over the package in February, I noticed that the $localKey parameter didn't actually do anything useful. So I removed most of its occurrences. The remaining ones are only there to prevent breaking changes in method signatures.

Eyewash01 commented 5 years ago

Oh ok - it just means in my case it's not usable, as the localkey on my main table is not "id".

Schema:

vehicles

fleets

fleet_ownercodes

I want to be able to link a vehicle to a fleet, via the owner_code, through the fleet_ownercodes table - i.e.

class Vehicle { public function fleet() { return $this->belongsToThrough(Fleet::class, OwnerCode::class); } }

staudenmeir commented 5 years ago

You basically want to define a BelongsToMany relationship with a single result?

Eyewash01 commented 5 years ago

No because a vehicle can only belong to a single fleet, just as a post only belongs to one country, in the classic example of this problem.

This plugin would be perfect for it, if it allowed a bespoke localkey, like for example Laravel does in the hasManyThrough relation, and I'm guessing why it was originally included in this plugin.

staudenmeir commented 5 years ago

What version of Laravel are you using?

Eyewash01 commented 5 years ago

5.5

staudenmeir commented 5 years ago

Laravel 5.8 has a HasOneThrough relationship that would fit your needs.

Until then, you can use my other package: https://github.com/staudenmeir/eloquent-has-many-deep

class Vehicle extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function fleet()
    {
        return $this->hasOneDeep(
            Fleet::class,
            [OwnerCode::class],
            ['code', 'id'],
            ['owner_code', 'fleet_id']
        );
    }
}
Eyewash01 commented 5 years ago

Ah that looks interesting - thanks very much I'll check it out

staudenmeir commented 5 years ago

Does the HasOneDeep relationship work for you?