Chron's avatar

New table or a field instead?

I have Person and Cars table.

Person could own multiple Cars. Person 1:M Cars

But what if I want to ask, what Car does the Person "currently driving"? Person 1:1 Cars

I thought of having a boolean field called driving in Cars table but I don't know. Should I create another table named Driving or something that holds both Person and Cars id? Or maybe a field driving_id in Persons table?

1 like
12 replies
Snapey's avatar

I would add current_car_id to the persons table and make this a belongs to relationship with the cars table

Glukinho's avatar

And make this column unique as a car can't be driven by a several drivers at the same time.

1 like
Chron's avatar

Would that create cyclic dependency? Person holds id from Cars, and vice versa.

1 like
Glukinho's avatar

No, models can have any number of relations with any models (including itself) as long as different columns are used.

You have two relation types between persons and cars:

  1. ownership: a person owns one or more cars; a car is owned by a single person
  2. driving: a person is driving a single car; a car is being driven by a single person

Use different columns for these relations and they exist separately.

martinbean's avatar

But what if I want to ask, what Car does the Person "currently driving"? Person 1:1 Cars I thought of having a boolean field called driving in Cars table but I don't know. Should I create another table named Driving or something that holds both Person and Cars id? Or maybe a field driving_id in Persons table?

@chron In this case, I’d say you’ve instead found a new entity in your system. You’re wanting to record some sort of “trip” or “journey”, that would have foreign keys pointing to the driver and what car they drove to complete the journey/trip.

1 like
dipeshkhanal79's avatar

Go for new column and add belongsTo Relation. Make it as simple as possible.

jlrdw's avatar

If a trip to point X was taken, entering that cars unique id in a field for the trip would work. But there are of course several ways do do such things.

Please or to participate in this conversation.