Laravel:遵循一个模型的第二个关系

Laravel: follow the second relationship of a model

我正在尝试访问票证的关系以提供设备和房间列表,但我无法使其正常工作。

你应该给我房间(包括设备)。

在枢轴table中,可以是room_id(指整个房间时),也可以是Device_id(仅指特定设备时),如果这个另一个应该是 Null

分成2份table会不会更好?一个用于设备,一个用于房间?或者是否可以通过关系来做到这一点?

非常感谢! :D

helpdesk_rooms
  id
  name


helpdesk_devices
  id
  name
  room_id


helpdesk_tickets_rooms_devices
  ticket_id
  room_id (Null when Device ID is set)
  device_id (Null when Room ID is set)

helpdesk_tickets
  id
  name
Device HasOne Room

Ticket HasMany Devices
Ticket HasMany Rooms 

class Device extends Model
{
    
    protected $table = 'helpdesk_devices';
    //public $primaryKey = null;
  
    public function deviceRoom()
    {
        return $this->hasOne(Room::class);
    }
class Ticket extends Model
{
    protected $table = 'helpdesk_tickets';


    public function roomsDirect()
    {
        return $this->hasManyThrough(
            Room::class,
            TicketRoomDevice::class,
            'ticket_id', // Foreign key on the TicketRoomDevice table...
            'id', // Foreign key on the Rooms table...
            'id', // Local key on the Ticket table...
            'room_id' // Local key on the TicketRoomDevice table...
        );
    }

    // How to get the Room name from Device -> Room (Name) ??    
    public function roomsDevices()
    {
        return $this->roomsDirect()-> ???;

    }

这种情况的最佳方法,在laravel中是通过多态关系解决的。

在您提出的示例中,它将是这样的:

helpdesk_rooms

  • 编号
  • 姓名

helpdesk_devices

  • 编号
  • 姓名
  • room_id

helpdesk_tickets

  • ticket_id
  • tickeable_id
  • tickeable_type
    class Device extends Model
    {
        public function ticket()
        {
            return $this->morphOne(Ticket::class, 'tickeable');
        }
    }
    
    class Room extends Model
    {
        public function ticket()
        {
            return $this->morphOne(Ticket::class, 'tickeable');
        }
    }
    
    class Ticket extends Model
    {
        public function tickeable()
        {
            return $this->morphTo();
        }
    }

除了节省更复杂的表和配置之外,这将使您能够轻松地处理其他关系。 更多内容可以查看官方文档polymorphic-relationships