Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cracker182's avatar

Relation 3 Tables (Article, Group, Article_Group)

Hi Everyone,

my head dont understand the following:

I have a table Articles and a table groups.

now i want to assign articles to the groups. I know that the table have to look like this

id  |  article_id  |  group_id
+++++++++++++++++++++

but i do not know the relation.

One Article can have One group (one-to-one) One Group can have many articles (one-to-many) but i have to use the lookup-table (article_group) to assign these articles.

Can anybody give me a push in the right direction?

I thank you for your help.

Dennis

[EDIT] I forgot to mention, that i can not extend the articles table with the group_id field, because i only have read access to this table.

0 likes
4 replies
joaomantovani's avatar
Level 2

Hello, if you are using eloquent, you don't need to fill the article_group table.

You just need to fill the relationships in your models, like that:

class Group extends Model
{
    /**
     * The articles that belong to the group.
     */
    public function articles()
    {
        return $this->belongsToMany('App\Article');
    }
}
class Article extends Model
{
    /**
     * The group that belong to the article.
     */
    public function group()
    {
        return $this->belongsToMany('App\Group');
    }
}

After that, the eloquent will do the job for you!

For example, to get the all the articles inside a group:

$articles = App\Group::find(1)->articles()->orderBy('name')->get();

Don't forget to import the models in your class too!

In the Article.php

use App\Group;

In the Group.php

use App\Article;

Here is the link to the docs:

https://laravel.com/docs/5.4/eloquent-relationships#many-to-many

1 like
cracker182's avatar

Thank you for your reply. I forgot to mention, that i can not extend the articles table with the group_id field, because i only have read access to this table.

joaomantovani's avatar

Oh, now I don't know how to help you, did you try it? Any errors?

1 like
cracker182's avatar

Hi, i solved it by using an "article_details" table, wich holds the needed additional infomation.

I've created a relation on articles (has one articledetails) and one relation on articledetails (has one group). This is the way you mentioned.

Thank you for your Help!

1 like

Please or to participate in this conversation.