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

ryan_160289's avatar

Eloquent Relationship with ID and link

I would like to create relationship two table with id. I have tables following:

categories

id  |name      |
----------------
1   |Category A|
2   |Category B|
3   |Category C|
4   |Category D|
5   |Category E|

sales
id |customer   |region       |product       |category_id
-------------------------------------------------------
1   James       Region A      Fruits         1,2,5
2   Billy       Region B      Vegetable      3,2,4
3   Benny       Region C      Computer       2,3,1

This is the relation function:

class Category extends Model
{
    public function sales ()
    {
        return $this->hasMany('App\Model\Sale');
    }
}

class Sale extends Model
{
    public function categories ()
    {
        return $this->belongTo('App\Model\Category');
    }
}

Desire result to view is:

customer   |region       |product       |Link to Category
-------------------------------------------------------
James       Region A      Fruits         Category A, Category B, Category E
Billy       Region B      Vegetable      Category C, Category B, Category D
Benny       Region C      Computer       Category B, Category C, Category A

And I want create link in column Link to Category where each category have a link to show category.

Could anyone show the way..? Thanks in advance.

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

You need a Many to Many relationship since Sale has many Category and Category has many Sale

categories

id  |name      |
----------------
1   |Category A|
2   |Category B|
3   |Category C|
4   |Category D|
5   |Category E|

sales
id |customer   |region       |product      
-------------------------------------------------
1   James       Region A      Fruits      
2   Billy       Region B      Vegetable  
3   Benny       Region C      Computer  


category_sale  pivot table

category_id | sale_id
------------------------
   1        | 1
   2        | 1
   5        | 1
   3        | 2
   2        | 2
   4        | 2
   2        | 3
   3        | 3
   1        | 3


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

Models

class Category extends Model
{
    public function sales ()
    {
        return $this->belongsToMany('App\Model\Sale');
    }
}

class Sale extends Model
{
    public function categories ()
    {
        return $this->belongsToMany('App\Model\Category');
    }
}

Please or to participate in this conversation.