首页 > 解决方案 > 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
]);

我如何才能在没有设备信息的情况下仅获取变量?

标签: phpmysqllaraveleloquent

解决方案


也许是这样的:

$variables = auth()->user()->devices()->with('variables')->get();

这将急切地加载设备所拥有的关系。

对于仅访问用户变量,您可以使用文档中提到的 has-many-throught 关系:

https://laravel.com/docs/5.7/eloquent-relationships#has-many-through


推荐阅读