PostgreSQL Articles

Laravel Eloquent ORM Polymorphism Examples

0 👍
👎 0
 Laravel
 PHP
 PostgreSQL
 MySQL

Laravel Eloquent ORM Polymorphism

In Laravel's Eloquent ORM, polymorphism refers to polymorphic relationships, which allow a model to belong to more than one type of model using a single association.

This is useful when you have a relationship that can apply to multiple different models without having to create separate foreign keys or pivot tables for each type. Examples would be Users and Products that each have one or more images.

Let’s take a look at different types of polymorphic relationships commonly used in Laravel Eloquent ORM.

 

One-to-One (Polymorphic)

Example: An Image model could belong to either a User or a Product.

 
// Image model

public function imageable()

 {

    return $this->morphTo();

 }

 

 // User model

public function image()

 {

    return $this->morphOne(Image::class, 'imageable');

 }

 

 // Product model

public function image()

 {

    return $this->morphOne(Image::class, 'imageable');

 }

 

Table Definitions: User, Product models can both have an Image.  Notice Image.imageable_id and Image.imageable_type.  This can join on both User.id and Product.id tables.

 

CREATE TABLE users (

   id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(255),

   email VARCHAR(255) UNIQUE

 );

 

CREATE TABLE products (

   id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(255),

   price DECIMAL(10,2)

 );

 

CREATE TABLE images (

   id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    url VARCHAR(255),

   imageable_id BIGINT UNSIGNED,  -- FK ID (user.id or product.id)

   imageable_type VARCHAR(255),   -- Model class (App\Models\User/App\Models\Product)

    INDEX idx_imageable (imageable_id, imageable_type)

 );

 




One-to-Many (Polymorphic)

Example: A Comment model could belong to both a Post and a Video.

 

 // Comment model

public function commentable()

 {

    return $this->morphTo();

 }

 

 // Post model

public function comments()

 {

    return $this->morphMany(Comment::class, 'commentable');

 }

 

 // Video model

public function comments()

 {

    return $this->morphMany(Comment::class, 'commentable');

 }

 

 

Table Definitions: Post, Video models can both have a Comment.  Notice Comment.commentable_id and Comment.commentable_type.  This can join on both Post.id and Video.id tables.

 

CREATE TABLE posts (

    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

   title VARCHAR(255),

   body TEXT

 );

 

CREATE TABLE videos (

    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    title VARCHAR(255),

    url VARCHAR(255)

 );

 

CREATE TABLE comments (

    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    body TEXT,

    commentable_id BIGINT UNSIGNED, -- FK ID (post.id|video.id)

    commentable_type VARCHAR(255), -- Model class (App\Models\Post|App\Models\Video)

    INDEX idx_commentable (commentable_id, commentable_type)

 );

 



Many-to-Many (Polymorphic)

Example: A Tag model can be applied to both Post and Video.

 

 // Tag model

public function posts()

 {

    return $this->morphedByMany(Post::class, 'taggable');

 }

 

public function videos()

 {

    return $this->morphedByMany(Video::class, 'taggable');

 }

 

 // Post model

public function tags()

 {

    return $this->morphToMany(Tag::class, 'taggable');

 }

 

 // Video model

public function tags()

 {

    return $this->morphToMany(Tag::class, 'taggable');

 }

 



Table Definitions: Both Post, Video models can have multiple Tags.  Also, a Tag can belong to multiple Post, Video models.  Notice the pivot table taggables…   

 

CREATE TABLE tags (

    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(255) UNIQUE

 );

 

CREATE TABLE posts (

    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    title VARCHAR(255),

    body TEXT

 );

 

CREATE TABLE videos (

    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    title VARCHAR(255),

    url VARCHAR(255)

 );

 

CREATE TABLE taggables (

    tag_id BIGINT UNSIGNED,    -- FK to tags.id

    taggable_id BIGINT UNSIGNED, -- FK ID (post.id or video.id)

    taggable_type VARCHAR(255), -- Model class (App\Models\Post / App\Models\Video)

    PRIMARY KEY (tag_id, taggable_id, taggable_type),

    INDEX idx_taggable (taggable_id, taggable_type)

 );

 




How to Backup and Restore with pg_dump and mysqldump

0 👍
👎 0
 Database
 PostgreSQL
 MySQL

This tutorial guides you through backing up MySQL and PostgreSQL databases from the command line. While their native tools—mysqldump and pg_dump—share a similar purpose, their command syntax differs. We will cover the essential commands for both systems, highlighting their key similarities and differences. 

Backup MySQL / MariaDB Database

 

Export every table’s schema and existing records to an SQL executable script.


mysqldump -u username -p database_name > database.sql

 

This will export the specified table’s schema and records to an executable script.

 

 mysqldump -u username -p database_name table_name > db_table.sql

 

 

This will export the specified table’s data only(no schema).

 
mysqldump -u username -p --no-create-info database_name table_name > table_data.sql

 

 

This will export the specified table’s schema only(no data).


mysqldump -u username -p --no-data database_name table_name > table_schema.sql

 

Restore MySQL / MariaDB Database

 

 mysql -u username -p database_name < database.sql

 

 

Backup PostgreSQL Database

 

Export every table’s schema and existing records to an SQL executable script.

 

 pg_dump -U username database_name > database.sql

 

 

This will export both the specified table’s schema and data to an executable script.

 

 pg_dump -U username -t table_name database_name > table.sql

 

 

Only data (no schema):

 

 pg_dump -U username -a -t table_name database_name > table_data.sql

 

 

Only schema (no data):

 

 pg_dump -U username -s -t table_name database_name > table_schema.sql


Restore PostgreSQL Database

 

 psql -U username -d database_name -f database.sql

 




PostgreSQL many-to-many Relationship

0 👍
👎 0
 PostgreSQL

In this example we will look at how to work with a many-to-many relationship.  So first let’s look at a situation where we can leverage a many-to-many relationship.  Imagine we have both Students and Courses.  A student can be enrolled in multiple courses and a course can have multiple students.  This is called a many-to-many relationship and requires what’s called a pivot table.  Although there aren’t any restrictions to the name of a pivot table I will call it “course_student”.  The course_student pivot table will have, at minimum, 2 foreign key fields.  A reference to courses table and a reference to students table.  

 

 

 CREATE TABLE students (

   id INT PRIMARY KEY AUTO_INCREMENT,

   name VARCHAR(100) NOT NULL,

   phone_number VARCHAR(100) UNIQUE NOT NULL,

 

 );

 

 CREATE TABLE courses (

   id INT PRIMARY KEY AUTO_INCREMENT,

   title VARCHAR(100) NOT NULL,

   description TEXT NOT NULL

 );

 

 -- The pivot table has a reference key to each table

 CREATE TABLE course_student (

   student_id INT,

   course_id INT,

   PRIMARY KEY (student_id, course_id),

   FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,

   FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE
);

 

Below are a few useful ways to query this schema. Assuming you are familiar with a LEFT JOIN, these queries specifically use LEFT JOIN for connecting the three tables. courses to course_student to students


# Get all courses that student with id = 2 is enrolled

SELECT c.id course_id, c.title, s.id student_id, s.name

FROM students s

LEFT JOIN course_student cs ON s.id = cs.student_id

LEFT JOIN course c ON c.id = cs.course_id

WHERE s.id = 2;

 

# Get all students enrolled in course with id = 1

 SELECT c.id course_id, c.title, s.id student_id, s.name

 FROM courses c

 LEFT JOIN course_student cs ON c.id = cs.course_id

 LEFT JOIN student s ON s.id = cs.student_id

 WHERE c.id = 1;