获取尾随枢轴的结果 table

Getting the result of a trailing pivot table

基本上,我有三个表,它们是 userspositionuser_position,我想让所有用户都拥有各自的 positions
请注意,一个用户可以拥有多个职位

    The `user_position` table consists of: 
    - user_id
    - position_id

为了说明...它是这样的:

users-->user_position<--position

到目前为止我得到的是:

用户模型

public function user_positions() {
    return $this->hasMany('App\Models\UserPosition', 'user_id', 'id');
}

用户位置模型

public function positions() {
    return $this->hasMany('App\Models\Position', 'position_id', 'id');
}

用户控制器

public function getallusers() {
    $data = User::with('user_positions')->get();
    return response()->json($data);
}

到目前为止,它给了我正确的结果集。 例如:

[{id:1,
  name:'John',
  user_positions:
    [{id:1, 
      user_id:1, 
      position_id: 5
     },
     {id:2, 
      user_id:1, 
      position_id: 9
     }
    ]
 }]

但是,它是不完整的,我还想要 user_positions 数组中的 positions 数组,但我不知道,或者我不知道如何 associate/merge/attach(我不知道知道正确的术语)我的 User 模型的 positions 函数。

您要查找的是 BelongsToMany 关系。

您可以将以下关系添加到您的 User 模型。

public function positions()
{
    return $this->belongsToMany(Position::class);
}

您可以通过以下方式预先加载它们:

User::with('positions')->get();

结果:

[{
    ...
    "positions": [{ ...The data of the position... }]
}]

当你想要 m:m 关系时,建议使用 BelongsToMany,不需要中间模型用于“透视”table。

如果您有 non-eloquent 标准命名约定。然后您必须在第二个参数中指定 table 名称,如下所示:

return $this->belongsToMany('App\Models\Positions', 'tbl_positions_assigned');

在第三个和第四个参数中指定外键名称。

我想请您参考文档 Eloquent-relationships,因为那里有非常详尽的解释。

您可以使用 belongsToMany 做的一件非常重要的事情是在数据透视 table 中附加额外的列。这些也很容易从枢轴 table 获得。如果您希望存储特定于模型的额外数据值,这将很有用。

return $this->belongsToMany('App\Models\Positions')->wherePivot('active', 1);

在上面的示例中,当您从查询中检索结果时,您可以排除某些值,在本示例中这些值不是 active