Laravel: проблема с обновлением, когда у клиента несколько записей - PullRequest
0 голосов
/ 29 апреля 2020

У меня есть три таблицы device_companies, devices & device_inventory, связанные с отношениями и загруженные ajax при создании и обновлении клиента. Однако загружаются только доступные данные, которые управляются таблицей subscriber_devices.

Часть create работает должным образом. Но при обновлении все devices, связанные с выбранным клиентом, загружаются. Например: если customer имеет ABC -> DEF -> A1,A2,A3, а я обновляю данные A2, то A1,A3 не должно отображаться в раскрывающемся списке. Только A2 и A4,A5,A6,... должны загружаться.

Таблицы:

device_companies:  ->  devices:                ->  device_inventories:
|-- id                 |-- id                      |-- id
|-- title              |-- device_company_id       |-- device_id
...                    |-- title                   |-- serial_number
                       ...                         ...

subscriber_devices:
|-- id
|-- subscriber_id
|-- device_inventory_id
...

DeviceCompany:

public function devices()
{
  return $this->hasMany(Device::class);
}

public function _dropdown($useWith = null, $subscriber = null)
{
  $Self = self::where('status', \Common::STATUS_ACTIVE)->select([
    'id',
    'title'
  ])->orderBy('title', 'ASC');

  # with relations
  if($useWith == true)
    $Self = $Self->whereHas('devices.deviceInventory', function($q) use ($subscriber) {
      $q->whereDoesntHave('subscriberDevice', function($q) use ($subscriber) {
        if(!is_null($subscriber))
          $q->where('subscriber_id', '!=', $subscriber->subscriber_id);
      });
    });

  # building query
  $Self = $Self->get();

  return ($Self->isEmpty() == false)
    ? $Self->toArray()
    : null;
}

Устройство:

public function deviceCompany()
{
  return $this->belongsTo(DeviceCompany::class);
}

public function deviceInventory()
{
  return $this
    ->hasMany(DeviceInventory::class)
    ->where('status', \Common::STATUS_ACTIVE)
    ->orderBy('serial_number', 'ASC');
}

public function _dropdown($deviceCompanyId, $useWith = null, $subscriber = null)
{
  $Self = self::select([ 'id', 'title' ])->where([
    'device_company_id' => $deviceCompanyId,
    'status'            => \Common::STATUS_ACTIVE
  ])->orderBy('title', 'ASC');

  # with relation
  if($useWith == true)
    $Self = $Self->whereHas('deviceInventory', function($q) use ($subscriber) {
      $q->whereDoesntHave('subscriberDevice', function($q) use ($subscriber) {
        if(!is_null($subscriber))
          $q->where('subscriber_id', '!=', $subscriber->subscriber_id);
        });
    });

  # building query
  $Self = $Self->get();

  return ($Self->isEmpty() == false)
    ? $Self->toArray()
    : null;
}

DeviceInventory:

public function subscriberDevice()
{
  return $this->hasOne(SubscriberDevice::class);
}

public function _dropdown($deviceId, $useWith = null, $subscriber = null)
{
  $Self = self::select([
    'id',
    'serial_number AS title'
  ])->where([
    'device_id' => $deviceId,
    'status'    => \Common::STATUS_ACTIVE
  ])->orderBy('title', 'ASC');

  # with relations
  if($useWith == true)
    $Self = $Self->whereDoesntHave('subscriberDevice', function($q) use ($subscriber) {
      if(!is_null($subscriber))
        $q->where('subscriber_id', '!=', $subscriber->subscriber_id);
    });

  # building query
  $Self = $Self->get();

  return ($Self->isEmpty() == false)
    ? $Self->toArray()
    : null;
}

SubscriberDevice:

public function subscriber()
{
  return $this->belongsTo(Subscriber::class);
}
public function deviceInventory()
{
  return $this->belongsTo(DeviceInventory::class);
}

Ответ (текущий):

{
    0: "-- Device Inventory --",
    1: "A1",
    2: "A2",
    3: "A3",
    4: "A4",
    5: "A5",
    6: "A6",
}

Текущий пользователь имеет три inventories связанных с ним A1, A2 & A3.
inventory, выбранный для редактирования, A2.
Доступно A4, A5 & A6 inventories, которое можно выбрать.

Следовательно, ожидаемый результат:

{
    0: "-- Device Inventory --",
    2: "A2",
    4: "A4",
    5: "A5",
    6: "A6",
}

1 Ответ

0 голосов
/ 06 мая 2020

Ну, это заняло у меня некоторое время. Но я решил проблему. Вот мой окончательный код ...

public function _dropdown($deviceId, $useWith = null, $subscriber = null)
{
  ...

  # with relations
  if($useWith == true)
    $Self = $Self->whereDoesntHave('subscriberDevice', function($q) use ($subscriber) {
      if(!is_null($subscriber))
        $query->where('token', '!=', $subscriber->token);
    });

  ...
}

Оказывается, единственное, что нужно было изменить, - это столбец условия where с subscriber_id до token. token является уникальным идентификатором записи inventory подписчика, которая редактировалась.

Надеюсь, что это может кто-то с аналогичной проблемой.

...