L
L
l03d2021-06-04 11:07:35
Laravel
l03d, 2021-06-04 11:07:35

How to arrange relationships with such a Laravel table?

There are three models:

  1. Event
  2. Subject
  3. Speaker


It is necessary to organize the following logic: an event can contain several topics, each topic contains several speakers. All this must be placed in a database table in this form:
event_id | topic_id | speaker_id
    1    |    1     |    1    
    1    |    1     |    2
    1    |    2     |    5
    2    |    1     |    3


Can you please tell me how best to organize this without changing the structure of the table?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
walkerstech, 2021-06-04
@walkerstech

Add the event_id row to the topic table Add the topic_id row to the
speaker table Add the topic_id row to
the event model

public function topic()
    {
        return $this->hasMany(Topic::class, 'event_id', 'event_id');
    }

To the topic model
public function event(): BelongsTo
    {
        return $this->belongsTo(Event::class, 'event_id', 'event_id');
    }
    public function speaker()
    {
        return $this->hasMany(Speaker::class, 'topic_id', 'topic_id');
    }

speaker model
public function topic(): BelongsTo
    {
        return $this->belongsTo(Topic::class, 'topic_id', 'topic_id');
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question