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

Niely's avatar
Level 1

Manytomany relation

Hi

I'm working in Laravel and need help with database relations. I have three tables: [b]projects:[/b] [code] +------------+--------------------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+--------------------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | title | varchar(191) | NO | | NULL | | | url | varchar(191) | YES | | NULL | | | updated | bigint(20) unsigned | YES | | NULL | | | type | enum('adobe','invision','pdf') | NO | | NULL | | | preview_id | int(10) unsigned | YES | MUL | NULL | | +------------+--------------------------------+------+-----+---------+----------------+ [/code]

[b]users:[/b] [code] +----------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | name | varchar(255) | NO | | NULL | | | email | varchar(150) | NO | UNI | NULL | | | password | varchar(179) | NO | UNI | NULL | | | remember_token | varchar(100) | YES | | NULL | | +----------------+------------------+------+-----+---------+----------------+ [/code]

[b]projects_users:[/b] [code] +------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | project_id | int(10) unsigned | YES | MUL | NULL | | | user_id | int(10) unsigned | NO | MUL | NULL | | +------------+------------------+------+-----+---------+----------------+ [/code]

Situation: There are several projects, and multiple users can work on multiple projects (ManyToMany). I need to select (SELECT-statement) all users working on project with e.g ID 1. How would I do that in plain SQL, and how would I do that in Laravel code (without a raw-sql-query function).

Thanks!

0 likes
1 reply
Screenbeetle's avatar

sorry bit rushed but roughly you'll need to firstly define the relation:

// projects.php model
public function users()
{
        return $this->belongsToMany(User::class);
}

then in your user.php model

public function projects()
{
    return $this->belongsToMany(Project::class);
}

untested but this should then let you do things like

$project = Project::find($id);
$users = $project->users()->pluck('name', 'id');
       

Sorry you'll have to play about a bit but that is the rough idea I believe

Please or to participate in this conversation.