问题描述:

Imagine you had a class like

class Person {

public $id;

public $name;

public $cars = array();

}

Where $cars is an array of cars (e.g. array('mercedes', 'toyota')).

How would you store that data in the database so that the array can be searched (e.g. select all persons that have a Toyota) and the entirely filled objects are retrieved with the same query (e.g fetch all the other cars that belong to those persons too).

Edit:

By "storing the object" I meant its data.

网友答案:

Create a tables called person and one called car and a linking table called car_person

  CREATE TABLE `car` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
       `name` varchar(32) DEFAULT NULL,
      PRIMARY KEY (`id`)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  CREATE TABLE `person` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
       `name` varchar(32) DEFAULT NULL,
      PRIMARY KEY (`id`)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;


   CREATE TABLE `car_person` (
    `car_id` int(11) unsigned NOT NULL,
      `person_id` int(11) NOT NULL,
        PRIMARY KEY (`car_id`,`person_id`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Also, make a Car class in your PHP :

class Car {
  public $id;
  public $name;
 }

Then use the array of cars in the Person class is an array of car objects, not names....

网友答案:

This is a typical many to many relationship. Example tables would be:

person:

id
name

person_vehicle:

id
person_id
car_id

vehicle:

id
manufacturer

You can find more design examples, as well as example queries, on this question.

相关阅读:
Top