Home > Back-end >  How to use raw SQL (DML and DDL) in Symfony projects?
How to use raw SQL (DML and DDL) in Symfony projects?

Time:01-25

I'm new in programming and I've built projects on xampp. There I created the databases in SQL (MARIADB) in 2 separated files (DML and DDL).

Now, learning Symfony I found that looks like I must use ORM to create the database. Can't I just create DML and DDL and connect/upload them to Symfony instead of using ORM?

I've been 2 days looking for information on how to do that, and I've just found ORM documentation. I wish I just could do something like this function:

 function mod001_conectoBD () {
        $address= "localhost";
        $user= "root";
        $password= "";
        $database   = "projectDDL"; //(which I uploaded on phpmyadmin as projectDDL.sql)
        
        $link = mysqli_connect( $address, $user, $password, $database );
        
        if ( !$link ) {
            echo "Fail connection";
        } 
        return $link;
    }

    function mod001_disconnectBD ( $link ) {
        
        mysqli_close( $link );
    }

This ofc is just the example i used on my xampp project. With this I just used the uploaded projectDDL.sql and built the app around it. Thanks and sorry for my ignorance in this matter.

The reason why I want this is building composite Primary keys, and editting id names, which i find so difficult on symfony.

Imagine for example a table that requires 3 foreign keys and its own id to have a 4 fields primary key, dont know how to make that possible in Symfony.

CodePudding user response:

to connect symfony to mariadb you must modify the .env file which is at the root of your project, for your case it will give something like this:

DATABASE_URL="mysql://[email protected]:3306/projectDDL"

symfony takes care of creating the database for you, and for each table you have to create an entity

you can create your database with this command on the shell:

php bin/console doctrine:database:create

CodePudding user response:

if you want to create a primary key made up of several foreign keys, doctirne allows you to do that I have already used in a project, you create an entity with foreign keys from your tables and you specify at the beginning that it is also an ID, ex :

#[Id, ManyToOne(targetEntity: User::class)]

#[Id, ManyToOne(targetEntity: Comment::class)]

#[Id, ManyToOne(targetEntity: Video::class)]

Documentation:

https://www.doctrine-project.org/projects/doctrine-orm/en/2.14/tutorials/composite-primary-keys.html#use-case-1-dynamic-attributes

  • Related