Search code examples
phplaravellaravel-bladedatamodel

Get second parent of child item Laravel Model


I have 3 model.

  1. Room - columns: id, name, isactive.

  2. Sensor - columns: id, name, isactive.

  3. RoomSensors - columns: id, roomid, sensorid, isactive.

I have models for all of them.

Room

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');
    }
}

Sensor

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

    protected $fillable = [];

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

RoomSensors

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');
    }

}

The page is not written by me, so I have to continue as it was made. And in blade I have the loop.

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

It must give me the info about sensor on the rooms, but it cant. So I need to get Warehouse_room -> Warehouse_roomsensor -> Warehouse_sensor


Solution

  • You need to add a new many-to-many relationship in your room model.

    Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany method. The belongsToMany method is provided by the Illuminate\Database\Eloquent\Model base class that is used by all of your application's Eloquent models. For example, let's define a sensors method on our WarehouseRoom model. The first argument passed to this method is the name of the related model class and the second argument would be the name of the intermediate 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');
        }
    }
    

    Once the relationship is defined, you may access the room's sensors using the sensors dynamic relationship property:

    use App\Models\WarehouseRoom;
    
    $warehouseRoom = WarehouseRoom::find(1);
    
    foreach ($warehouseRoom->sensors as $sensor) {
        //
    }
    

    In blade

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