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

AmineBHD's avatar

which relationship I should use to get category articles

I'm working on a small project and I would like to know what kind of relationship I need to use to get a list of my articles in a category

( by the way each article have only one category )

this is my articles table:

 id ,title, content, category_id

This is my categories table:

 id, name

and I have two models ( Article and Category ), so how I can get all the articles of category number 1 for example ( what kind of relationship I need )

0 likes
2 replies
ranjeetweb's avatar

You need to use One to one Relation (belongsTo) in Article Model and Category model in One to many (hasMany)

rodrigo.pedra's avatar

From your description it seems a Has Many relationship would do it:

class Category extends Model
{
    public function articles()
    {
        return $this->hasMany(Article::class);
    }
}
class Article extends Model
{
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}

Please or to participate in this conversation.