E
E
Eugene2019-08-26 20:14:59
Laravel
Eugene, 2019-08-26 20:14:59

How to do relationships in Laravel?

Good day.
There are tables users, codes, langs and themes.
I need to associate users with codes and codes with langs and themes.
In codes I do this:

$table->integer('lang_id')->unsigned();
$table->foreign('lang_id')->references('id')->on('langs');
$table->integer('theme_id')->unsigned();
$table->foreign('theme_id')->references('id')->on('themes');
$table->integer('lang_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');

In the User model, do hasMany(Codes::class);
And in Codes:
belongsTo(User::class)
The same in Langs and Themes, only belongsTo(Codes::class).
Am I doing it right and in general, is it possible to get by with simple joins?
The bottom line is that the user creates an entry in codes, in which langs and themes are attached.
So that later on the page to display data from langs and themes by their id.
You also need to display all user records from codes in his profile.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kirill Sannikov, 2019-08-27
@k-sannikow

Here, read at your leisure:
Here, in very simple terms, it talks about relationships in Laravel Eloquent.

A
Alexey Nikolaev, 2019-08-26
@Heian

You should always use an ORM if there is one. In Lara's case, Eloquent should always be used. This greatly simplifies development and makes the code cleaner and more readable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question