Laravel中的许多关系

时间:2017-03-18 12:25:50

标签: php sql laravel

我在Laravel工作,需要数据库关系方面的帮助。我有三张桌子:

项目:

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

用户:

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

情况:有多个项目,多个用户可以处理多个项目(ManyToMany)。 我需要选择(SELECT语句)所有使用例如ID 1的项目的用户。 我将如何在纯SQL中执行此操作,以及如何在Laravel代码中执行此操作(不使用raw-sql-query函数)。

我已经看过了here,但我还没找到它。

谢谢!

2 个答案:

答案 0 :(得分:0)

使用whereHas()方法:

$users = User::whereHas('projects', function($q) use($projectId) {
    $q->where('id', $projectId);
})->get();

答案 1 :(得分:-1)

class Project extends Model{
 public function users()
 {
    return $this->belongsToMany('App\User', 'projects_users');
 }
}

class User extends Model{
 public function projects()
 {
    return $this->belongsToMany('App\Project', 'projects_users');
 }
}
$project = Project::find(1);
$project->users //list of all the users