Database One-to-Many with two foreign key fields in Laravel -


i have been trying define database schema use laravel framework. want model football match. first step wanted define entity relationship diagram, found (which thought quite trivial) confusing in aspects.

first, obvious approach match related 2 teams, , team related number of matches. so, have "many many" relationship.

but implementation of many many relation have 2 tables , intermediate table relate both entities. think much, when know match have 2 teams , having 2 columns (local_id , visitant_id) foreign keys teams table enough. plus, want able match::find(1)->local() or match::find(1)->visitant()

so, thinking on implementing "one many" relation, have issue. retrieve matches team has played team::find(1)->matches(). cannot because can specify 1 key column when defining matches() method in eloquent (by default team_id, should visitant_id , local_id).

after more digging source code found there way keep database schema , achieve want (at least in laravel 4). posted problem in github , taylor otwell (creator of framework) gave me correct answer: https://github.com/laravel/framework/issues/1272

quoting him, should easy this:

class team extends eloquent  {     public function allmatches()     {         return $this->hasmany('match', 'visitant_id')->orwhere('local_id', $this->id);     } } 

and then...

$team = team::find(2); $matches = $team->allmatches; 

update: github link not working because laravel doesn't take bug reports in way more: http://laravel-news.com/2014/09/laravel-removes-github-issues/


Comments