Wednesday, October 1, 2008

Re: Database Conventions: 2 foreign keys to same table

Be careful with your $belongsTo definitions. The second one just
overwrote the first. If you want to create two relations you need to
use this syntax:

var $belongsTo = array(
'FromTeam' => array(
'className' => 'Team',
'foreignKey' => 'from_team_id'
),
'ToTeam' => array(
'className' => 'Team',
'foreignKey' => 'to_team_id'
)
);

Michael
On Oct 1, 5:12 am, "martin.westin...@gmail.com"
<martin.westin...@gmail.com> wrote:
> One simple thing I'd suggest is the naming of the fields team2_id does
> not tell me wether the trade is from or to this team.
> Something like from_team_id and to_team_id would make their role more
> obvious. At least imagine that is what a trade is in baseball... if
> they are always a bidirectional exchange then your team1 team2 would
> be fine.
>
> You can do the linking in this way:
> var $belongsTo = array(
>         'FromTeam' => array(
>             'className'    => 'Team',
>             'foreignKey'    => 'from_team_id'
>         )
> );
> var $belongsTo = array(
>         'ToTeam' => array(
>             'className'    => 'Team',
>             'foreignKey'    => 'to_team_id'
>         )
> );
> Your trade would now belong to two teams detified by their role in the
> transaction.
>
> For a bidirectional association I am not sure this kind of belongTo
> would find both teams (since it probably expects a single record).
> var $belongsTo = array(
>         'Team' => array(
>             'className'    => 'Team',
>             'foreignKey'    => false,
>             'conditions'     => 'Team.id = Transaction.team1_id OR
> Team.id = Transaction.team2_id'
>         )
> );
>
> You could probably do something similar using a hasMany or something
> if you had to.
>
> On Oct 1, 3:12 am, James <julesbr...@gmail.com> wrote:
>
> > I'm setting up a database that includes tracking of trades of baseball
> > teams. For the teams table I have:
>
> > CREATE TABLE teams (
> >         id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
> >         city VARCHAR(13),
> >         name VARCHAR(12),
> >         abbreviation VARCHAR(3)
> > );
>
> > I get lost when creating the trades table how do I set it up so
> > there's two foreign keys to the teams table? I'm trying to achieve
> > something along the lines of this:
>
> > CREATE TABLE trades (
> >         id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
> >         team2_id INT UNSIGNED NOT NULL,
> >         team1_id INT UNSIGNED NOT NULL
> > );
>
>
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---

No comments: