staudenmeir / belongs-to-through

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

Add the ability to use a non standard foreign key in relations #10

Closed dannyweeks closed 8 years ago

dannyweeks commented 8 years ago

Currently the foreign key has to be the singular of the table name.

I have made changes to allow an array to be passed in as the through model with a reference to the model and the intended foreign key.

In the tests I have added another table called offshore_states. The district still uses the foreign key state_id. The assumed foreign key would be offshore_state_id which would return an sql error. To overwrite this the model reference is put inside an array with the second element being a string the foreign key.

// Stub_Test_Model_City class

    public function offshoreCountry()
    {
        return $this->belongsToThrough(Stub_Test_Model_Country::class,
            [[Stub_Test_Model_Offshore_State::class, 'state_id'], Stub_Test_Model_District::class]);
    }

As you can see the 'through' is inside another array otherwise it would think the given foreign key is another model.

Id love to know your thoughts on this. If you would like I could add this addition to the readme file too.

Danny

znck commented 8 years ago

:+1: Nice

dannyweeks commented 8 years ago

✊ Happy to help! The cs kicked my arse, first time I have picked a fight with StyleCI 😁

znck commented 8 years ago

Thanks :smile:

This takes care of that.

composer global require fabpot/php-cs-fixer
php-cs-fixes --level=psr2 *.php