P
P
pemi2017-07-13 15:53:08
MySQL
pemi, 2017-07-13 15:53:08

In Laravel, does everything in the database have to be entities?

Here I have a User model. A user can have several links to social media accounts. The site can support 3 social networks so far. For bindings, I store the following data in the users_socials table - user - service(enum) - id_in_service . So, due to the fact that there are few social networks (there are only 3 of them), I use enum and do not create a row in a separate table for each social network. It is right? Or is it necessary to create a separate Social model and use relations to connect the social network and the user? Won't Taylor punish me for this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
JhaoDa, 2017-07-13
@pemi

Yes, it would be right to get rid of enums, create a separate Social model and use links to connect the social network and the user.
No, not everything in the database should be entities, but in this case it is convenient.

I
Igor Vorotnev, 2019-07-28
@HeadOnFire

1. Enums are not very good, don't use them. Then refactor more crap than convenience / benefit from them.
2. Not everything has to be entities, but basically yes - it's more convenient.
3. In your case, in the simplest implementation, this is the relationship oneToMany - User hasMany Socials / Social belongsTo User (additional data is stored in the socials table): Users
table : Socials table :id | email | ...
But here you will have duplication of all data for each social network - starting from the title field and further (and what is there depends on the project. It is quite possible that there is also an API key, maybe an icon, url, etc.). Therefore, such a database will not be adequately normalized. If you have more than 1 name / title field on the social network, then it is more reasonable to make a manyToMany connection using pivot.
Relationship manyToMany - User belongsToMany Socials / Social belongsToMany Users (additional data diverge by tables - everything that is unique to Social in socials, everything about the relationship - in pivot): users
table : socials table : social_user table :id | email | ...
In models:

// User
public function social()
{
    return $this->belongsToMany(Social::class)->withPivot(['external_social_id']);
}
    
// Social
public function user()
{
    return $this->belongsToMany(User::class)->withPivot(['external_social_id']);
}

If such a dynamic connection entity grows and becomes more complex over time, we make it a full-fledged entity by creating our own model (class SocialUser extends Pivot).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question