auliamnaufal's avatar

Different relation for different column type

Hello, so now I'm facing a pretty confusing problem to structure my database so, I want to make a service table and that table has a relation to a couple of different other tables based on the service.

for example, the service that I want to choose is A, so that table has a relation to table A and fills the data there. Same if I choose service B, then that service has a relation to table B, etc.

why I want to create this, is because each service has a different column to fill, service A maybe has 10 columns, service B maybe has 5 columns to fill, etc and the table structure for each service relation has a different structure.

Can you give me the best solution for this issue? Thanks

0 likes
1 reply
LaryAI's avatar
Level 58

One solution to this problem is to use polymorphic relationships in Laravel. This allows a single table to have multiple types of relationships with other tables.

First, create a "services" table with a "serviceable_id" and "serviceable_type" column. The "serviceable_id" column will store the ID of the related record, and the "serviceable_type" column will store the class name of the related record.

Next, create the different tables for each service (e.g. "table_a", "table_b", etc.) with their respective columns.

Then, in each of the models for the different tables, define a morphMany relationship to the "services" table:

class TableA extends Model
{
    public function services()
    {
        return $this->morphMany(Service::class, 'serviceable');
    }
}

Finally, in the "Service" model, define the inverse morphTo relationship:

class Service extends Model
{
    public function serviceable()
    {
        return $this->morphTo();
    }
}

Now, when you create a new service for a specific table, you can use the morphMany relationship to associate it with the correct record:

$tableA = TableA::find(1);
$service = new Service;
$tableA->services()->save($service);

You can also retrieve the related service for a specific record using the morphOne or morphMany relationship:

$tableA = TableA::find(1);
$service = $tableA->services()->first();

Please or to participate in this conversation.