Zach Kauffman
Zach Kauffman

Reputation: 496

CakePHP relationship scenario

I'm trying to figure out the appropriate relationship setup/schema for the following scenario and I suppose I'm a bit unclear as to the relationships themselves.

My models: Accident and People.

An accident may involve many people. A person may be related to many accidents.

For example: An accident happens to Abe and Bob. Abe may be the related to multiple accidents.

I have an accidents table, a people table and an accidents_people table with the appropriate schema. I want the user to be able to add an accident independently of a person, and a person independently of an accident, and then when they edit an accident, link it to multiple people. Is this possible?

$people = $this->Accident->Person->find('list');  //should give me list of all people
$this->set('people', $people);  //should allow me to access a list of all people in view

Upvotes: 1

Views: 87

Answers (1)

Dave
Dave

Reputation: 29141

TLDR:

What you're describing is the "Has and Belongs To Many" relationship (also known as HABTM):

http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm


Note / Another option:

Another option is the HasMany Through, which is basically HABTM, but with a model specifically for the join table. This allows a bit more flexibility if you need more than just the 3 fields in your join table (id, person_id, and accident_id)


Model convention:

If you're following the CakePHP Model and Database Conventions, your "People" model should really be "Person".

It's "okay" to use non-standard, but if you're learning Cake, you're better off trying to stick to them for now.

(looking at your code, which correctly uses "Person" as the model, I assume you just typed it wrong in your description)

Upvotes: 2

Related Questions