Saturday, March 18, 2017

Manytomany relation in Laravel

I'm working in Laravel and need help with database relations. I have three tables:

projects:

+------------+--------------------------------+------+-----+---------+----------------+
| 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    |                |
+------------+--------------------------------+------+-----+---------+----------------+

users:

+----------------+------------------+------+-----+---------+----------------+
| 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    |                |
+----------------+------------------+------+-----+---------+----------------+

projects_users

+------------+------------------+------+-----+---------+----------------+
| 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    |                |
+------------+------------------+------+-----+---------+----------------+

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).

I already looked here but I ain't really catching it.

Thanks!



via O'Niel

Advertisement