Laravel, используя сводную таблицу в отношениях - PullRequest
1 голос
/ 10 июля 2019

Laravel 5.3, у меня есть эти две модели:

Пользователь, с такими отношениями:

public function newFunctions()
{
    return $this->belongsToMany('App\NewFunctions', 'user_newfunctions');
}

NewFunctions:

public static function getAllFunctions() {
    $functions = DB::table('new_functions as nf')
    ->select('nf.*')
    ->get();
    return $functions;
}

public function users(){
    return $this->belongsToMany('App\User', 'user_newfunctions', 'new_function_id', 'user_id');
}

(что getAllFunctions было там до того, как я получил этот код ... не говорите об этом, есть много других контроллеров, использующих этот метод ... Я не знаю, является ли его версия или нет, но какого черта старый программист не использовал вместо него all()

Затем в моем контроллере я делаю это:

$user = User::findOrFail($id);

foreach ($user->newFunctions as $key => $function) {
    //dd($function);
    $user_new_functions[] = [$function->id, 69];
}
dd($user_new_functions);

С dd($function); Я получаю это:

NewFunctions {#961 ▼
  #table: "new_functions"
  #connection: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:7 [▶]
  #original: array:9 [▶]
  #relations: array:1 [▼
    "pivot" => Pivot {#962 ▼
      #parent: User {#770 ▶}
      #foreignKey: "user_id"
      #otherKey: "new_functions_id"
      #guarded: []
      #connection: null
      #table: "user_newfunctions"
      #primaryKey: "id"
      #keyType: "int"
      #perPage: 15
      +incrementing: true
      +timestamps: false
      #attributes: array:2 [▼
        "user_id" => 814
        "new_functions_id" => 1
      ]
      #original: array:2 [▶]
      #relations: []

А с dd($user_new_functions); получаю:

array:2 [▼
  0 => array:2 [▼
    0 => 1
    1 => 69
  ]
  1 => array:2 [▼
    0 => 3
    1 => 69
  ]
]

Мне нужно вместо 69 передать значение function_count, которое находится в сводной таблице user_newfunctions

Вот эта таблица:

user_id | new_functions_id | function_count
-------------------------------------------
    814 |           1      |   5
    814 |           3      |   7

Так что у меня будет в dd($user_new_functions); это:

array:2 [▼
  0 => array:2 [▼
    0 => 1
    1 => 5
  ]
  1 => array:2 [▼
    0 => 3
    1 => 7
  ]
]

Этот массив - моя цель. Пожалуйста, помогите.

1 Ответ

1 голос
/ 10 июля 2019

Вы должны включить ->withPivot() метод в отношения:

User.php:

public function newFunctions(){
  return $this->belongsToMany('App\NewFunctions', 'user_newfunctions')->withPivot(['function_count']);
}

NewFunctions.php

public function users(){
  return $this->belongsToMany('App\User', 'user_newfunctions', 'new_function_id', 'user_id')->withPivot(['function_count']);
}

Теперь при запросе отношения будет доступно свойство ->pivot, содержащее все столбцы из метода ->withPivot(). Вы можете заменить 69 следующим:

$user = User::with(['newFunctions'])->findOrFail($id);
foreach ($user->newFunctions as $key => $function) {
  $user_new_functions[] = [$function->id, $function->pivot->function_count];
}
dd($user_new_functions);

Примечание: добавлено with(['newFunctions']) для быстрой загрузки (возможное увеличение производительности, но не обязательно)

В документации описывается, как получить столбцы промежуточной таблицы чуть ниже информации отношения «многие ко многим»: https://laravel.com/docs/5.8/eloquent-relationships#many-to-many

...