问题描述
我有 3 个模型。
-
房间 - 列:id、name、isactive。
-
传感器 - 列:id、name、isactive。
-
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','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');
}
}
@foreach($warehouse_room -> warehouse_roomsensors -> sortBy('index') as $sensor)
它必须给我关于房间传感器的信息,但它不能。 所以我需要得到 Warehouse_room -> Warehouse_roomsensor -> Warehouse_sensor
解决方法
您需要在房间模型中添加新的多对多关系。
多对多关系是通过编写一个返回 line-height
方法结果的方法来定义的。 belongsToMany
方法由 belongsToMany
基类提供,您的应用程序的所有 Eloquent 模型都使用该基类。例如,让我们在 WarehouseRoom 模型上定义一个传感器方法。传递给此方法的第一个参数是相关模型类的名称,第二个参数将是中间表的名称。:
Illuminate\Database\Eloquent\Model
一旦定义了关系,您就可以使用 <?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) {
//
}