Laravel多对多关系 - 链接3项

时间:2014-03-16 20:37:18

标签: database database-design laravel-4

我有users

|------------|
|   USERS    |
|------------|
|id          |
|f_name      |
|l_name      |
|------------|

现在这些用户可以相互联系 - 爸爸,兄弟,姐姐等

为此,我有relations

|------------|
|  RELATIONS |
|------------|
|id          |
|type        |
|------------|

现在我如何关联用户?我试过的是: 我创建了一个relation_user

|---------------|
| RELATION_USER |
|---------------|
|id             |
|user_id        |
|user2_id       |
|relation_id    |
|---------------|

型号:

Relation.php

public function user()
{
    return $this->belongsToMany('User');
}

User.php

public function relations()
{
    return $this->belongsToMany('Relation');
}

我尝试抓住这样的关系:

$u = User::find('11');
var_dump($u->relations->toArray());

这是我得到的:

array(1) {
  [0]=>
  array(5) {
    ["id"]=>
    string(1) "1"
    ["relation"]=>
    string(12) "Grand Father"
    ["pivot"]=>
    array(2) {
      ["user_id"]=>
      string(2) "11"
      ["relation_id"]=>
      string(1) "1"
    }
  }
}

请注意,它在数据透视表(relation_user)中缺少user2_id。我怎样才能获得第3场。这也是一个正确的数据库设计?谢谢。

我知道我可以做类似下面代码的事情。只想了解最佳实践/更好的方法。可能会利用eager loading并返回Laravel collection

$a = DB::table('relation_user')->where('user2_id', '=', '1')->get(array('user_id', 'user2_id', 'relation_id'));

2 个答案:

答案 0 :(得分:0)

好的,我的问题得到了很好的解决方案。这是我做的:

<强>型号:

Relation.php

public function user(){
    return $this->belongsToMany('User', 'relation_user', 'user_id', 'relation_id')->withPivot('user2_id')->withTimestamps();
}

User.php

public function relations() {
    return $this->belongsToMany('Relation', 'relation_user', 'user_id', 'relation_id')->withPivot('user2_id')->withTimestamps();
}

抓住这样的关系:

$user = User::find('11');
$user->relations->toArray();

给我以下输出:

array(1) {
  [0]=>
  array(5) {
    ["id"]=>
    string(1) "1"
    ["relation"]=>
    string(12) "Grand Father"
    ["created_at"]=>
    string(19) "2014-03-17 01:18:54"
    ["updated_at"]=>
    string(19) "2014-03-17 01:18:54"
    ["pivot"]=>
    array(5) {
      ["user_id"]=>
      string(2) "11"
      ["relation_id"]=>
      string(1) "1"
      ["user2_id"]=>
      string(1) "1"
      ["created_at"]=>
      string(19) "2014-03-17 02:02:43"
      ["updated_at"]=>
      string(19) "2014-03-17 02:02:43"
    }
  }
}

插入如下:

$user->relations()->attach(1, array('user2_id' => 2));

答案 1 :(得分:-1)

您需要更正您的模型类:

public function user()
{
    return $this->belongsTo('User'); //one relation entry correspond to one user
}

public function relations()
{
    return $this->hasMany('Relation'); //one user has multiple relations
}

//query the user and the relations
$u = User::find(11)->relations; // this will returns entries in relation table with user_id=11