php 不同连接上的HasOneThrough关系

eqoofvh9  于 2023-06-28  发布在  PHP
关注(0)|答案(1)|浏览(123)

我有这些模型

class Device extends Model
{
    use HasFactory;

    protected $connection = 'traccar';
    
   public function vehicle()
   {
       //Code I need
   }
}

class Vehicle extends Model
{
    use HasFactory;

    protected $connection = 'mysql';
  
}

class VehicleDevice extends Model
{
    use HasFactory;
    protected $connection = 'mysql';
}

正如你所看到的,设备在tracar数据库中,模型的重置在MySQL连接中。
如何编写设备与车辆的hasOneThrough关系?我得到一个错误,说

Table 'tracar.vehicles' doesn't exist (Connection: traccar, SQL: select * from `tc_devices` where exists (select * from `vehicles` inner join `vehicle_devices` on `vehicle_devices`.`id` = `vehicles`.`vehicle_device_id` where `tc_devices`.`id` = `vehicle_devices`.`device_id`))'
biswetbf

biswetbf1#

class Device extends Model
{
    use HasFactory;

    protected $connection = 'traccar';
    
    public function vehicle()
    {
        return $this->hasOneThrough(
            Vehicle::class,
            VehicleDevice::class,
            'device_id', // Foreign key on the VehicleDevice model
            'id', // Foreign key on the Vehicle model
            'id', // Local key on the Device model
            'vehicle_device_id' // Local key on the VehicleDevice model
        );
    }
}

通过定义此关系,您可以使用vehicle属性从Device示例访问关联的Vehicle模型。例如:

$device = Device::find(1);
$vehicle = $device->vehicle; // Retrieve the associated Vehicle model

相关问题