oscarotero / simple-crud

PHP library to provide magic CRUD in MySQL/Sqlite databases with zero configuration
MIT License
242 stars 58 forks source link

Do relations work if there's no actual FK? #23

Closed elieobeid7 closed 6 years ago

elieobeid7 commented 6 years ago

Without an actual foreign key, is it possible to make relations between table work? Redbeanphp style

oscarotero commented 6 years ago

I don't know what redbean do, but I suspect don't. Can you provide an example of what do you want?

elieobeid7 commented 6 years ago

It's a schemaless ORM

Let's say we have the following database scheme:

CREATE TABLE "post" (
    `id`    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    `title` TEXT,
    `category_id` INTEGER,
    `type`  TEXT,

    FOREIGN KEY(`category_id`) REFERENCES category(id)
);

CREATE TABLE `category` (
    `id`    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    `name`  TEXT
);

CREATE TABLE `tag` (
    `id`    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    `name`  TEXT
);

CREATE TABLE `post_tag` (
    `id`    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    `tag_id`   INTEGER NOT NULL,
    `post_id`  INTEGER NOT NULL,

  //  FOREIGN KEY(`tag_id`) REFERENCES tag(id),
 //   FOREIGN KEY(`post_id`) REFERENCES post(id) 
// Lets not create foreign keys
);

Can we still do this? I think we can't but this option is cool, although I'm against schemaless databases but sometimes I use it, sometimes it makes life easier

$post = $db->post;

oscarotero commented 6 years ago

Yes, you can. SimpleCrud follows only the naming conventions but whether the fields are declared as foreign key in the database is irrelevant, it is just an improvement in the database.

elieobeid7 commented 6 years ago

Perfect