php - Laravel 和 mySQL 与关系表
问题描述
我需要用 laravel 和 PHP 创建一个 API。我已经为GET
所有用户和GET
与用户相关的所有设备创建了 api 路由。
我在 mySQL 中制作了以下表格:
设备:
increments('id');
string('name');
longText('description');
用户与设备关系表:
increments('id');
unsignedInteger('user_id');
unsignedInteger('device_id');
foreign('user_id')->references('id')->on('users');
foreign('device_id')->references('id')->on('devices');
变量:
increments('id');
string('type');
unsignedInteger('device_id');
longText('description');
foreign('device_id')->references('id')->on('devices');
模型具有关系代码:
用户模型:
public function deviceVariables() {
return $this->hasMany('App\DeviceVariable');
}
public function devices()
{
return $this->belongsToMany('App\Device');
}
设备型号:
public function users()
{
return $this->belongsToMany('App\User');
}
public function variables()
{
return $this->hasMany('App\DeviceVariable');
}
最后是DeviceVariable 模型:
public function device()
{
return $this->belongsTo('App\Device');
}
public function user()
{
return $this->belongsTo('App\User');
}
我能够显示与经过身份验证的用户相关的所有设备,但我无法显示与与该用户相关的设备相关的所有变量。
这段代码(的索引方法DeviceVariablecontroller
)是我最接近获取变量的方法:
$counter = 1;
$arrayIndex = 0;
while($counter <= 10) {
if(auth()->user()->devices()->find($counter)) {
$variables[$arrayIndex] = auth()->user()->devices()->find($counter)->variables;
$arrayIndex++;
}
$counter++;
}
有没有办法制作一个包含所有用户设备 ID 的数组并通过它们循环? - 或者有没有更聪明的方法来获取所有用户设备的所有变量?
编辑: 评论让我得到了这两个设备以及每个设备变量。
$variables = auth()->user()->devices()->with('variables')->get();
return response()->json([
'success' => true,
'data' => $variables
]);
我如何才能在没有设备信息的情况下仅获取变量?
解决方案
也许是这样的:
$variables = auth()->user()->devices()->with('variables')->get();
这将急切地加载设备所拥有的关系。
对于仅访问用户变量,您可以使用文档中提到的 has-many-throught 关系:
https://laravel.com/docs/5.7/eloquent-relationships#has-many-through
推荐阅读
- python - Discord.py WELCOMER - 如何为欢迎消息制作自定义图像
- mongodb - 如何从与数组比较的数组字段中查找所有文档
- arrays - 无法解决 KlockWork 缓冲区溢出错误
- react-native - 来自 fetch API 响应的 React Native flatlist
- swift - 存储异构键路径数组
- firebase - 颤动访问文档内firestore中的列表
- node.js - 尝试访问nodejs中的内部字符串
- pandas - 新行是在熊猫数据框中使用 Groupby 的两行的差异
- python - 即使我设置了默认值,Argparse“需要参数”错误
- python - Python For 循环输出到列表中