获取第 parent 个 child 项 Laravel 模型

Get second parent of child item Laravel Model

我有3个模型。

  1. 房间 - 列:id、name、isactive。

  2. 传感器 - 列:id、name、isactive。

  3. RoomSensors - 列:id、roomid、sensorid、isactive。

我有所有模型。

房间

class WarehouseRoom extends Model
{
    protected $table = 'tempohub_rooms';

    protected $fillable = ['id','warehouseid','name','isactive','image'];

    public    $timestamps   = false;

    public function warehouse_roomsensors()
    {
        return $this -> hasMany('App\WarehouseRoomSensor','roomid');
    }

    public function warehouse()
    {
        return $this -> belongsTo('App\Warehouse','warehouseid','id');
    }
}

传感器

class Sensor extends Model
{
    protected $table = 'tempohub_sensors';

    protected $fillable = [];

    public function roomToSensor() {
        return $this -> hasMany('App\WarehouseRoomSensor', 'sensorid');
    }
}

房间传感器

class WarehouseRoomSensor extends Model
{
    protected $table = 'tempohub_roomsensors';

    protected $fillable = [];

    public    $timestamps   = false;

    public function sensor() 
    {
        return $this -> belongsTo('App\Sensor', 'sensorid', 'id');
    }

    public function room()
    {
        return $this -> belongsTo('App\WarehouseRoom','roomid','id');
    }

}

该页面不是我写的,所以我必须按原样继续。在 blade 我有循环。

@foreach($warehouse_room -> warehouse_roomsensors -> sortBy('index') as $sensor)

它必须给我关于房间传感器的信息,但它不能。 所以我需要得到 Warehouse_room -> Warehouse_roomsensor -> Warehouse_sensor

您需要在房间模型中添加新的 many-to-many 关系。

Many-to-many 关系是通过编写 returns belongsToMany 方法的结果的方法来定义的。 belongsToMany 方法由 Illuminate\Database\Eloquent\Model 基础 class 提供,您的应用程序的所有 Eloquent 模型都使用该方法。例如,让我们在 WarehouseRoom 模型上定义一个传感器方法。传递给此方法的第一个参数是相关模型的名称 class,第二个参数是中间模型的名称 table.:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class WarehouseRoom extends Model
{
    /**
     * The sensors that belong to the room.
     */
    public function sensors()
    {
        return $this->belongsToMany(Sensors::class, 'tempohub_roomsensors');
    }
}

定义关系后,您可以使用 sensors 动态关系访问房间的传感器 属性:

use App\Models\WarehouseRoom;

$warehouseRoom = WarehouseRoom::find(1);

foreach ($warehouseRoom->sensors as $sensor) {
    //
}

在blade

@foreach($warehouseRoom->sensors as $sensor)