В моем приложении есть несколько разных таблиц:
- inspections (простая таблица, которая содержит только идентификатор, дату и т. д.; все, что нам нужно от нее, это идентификатор)
- customers (таблица содержит идентификатор и другую информацию о клиенте)
- customer_types (таблица содержит различные типы клиентов, например, покупатель, агент покупателя и т. д.)
- inspection_customers_types (эта таблица относится к проверке [inspection_id], клиент [customer_id] и тип клиента [type_id])
Например:
Клиент {ID: 345 может принадлежать инспекции {ID: 10} с клиентом Тип {ID: 3 – агент покупателя
Клиент {ID: 345} может принадлежать инспекции {ID: 15} с типом клиента {ID: 1 – покупатель
На мой взгляд, я пытаюсь получить значение customer_types.type, но не могу его получить Чтобы работать, я думаю, что неправильно определил отношения, но не могу понять их правильно. Я перечислю свои отношения ниже:
Модель проверки
public function customers()
{
return $this->belongsToMany(Customer::class, 'inspection_customers_types')
->withPivot('type_id')
->withTimestamps();
}
Модель клиента
public function customerTypes()
{
return $this->belongsToMany(CustomerType::class, 'inspection_customers_types')
->withPivot('inspection_id')
->withTimestamps();
}
public function inspections()
{
return $this->belongsToMany(Inspection::class, 'inspection_customers_types')
->withPivot('type_id')
->withTimestamps();
}
Теперь мне не терпится загрузить проверку в свой контроллер:
$inspection->load('invoice', 'services', 'vendors', 'statusNotes', 'fileUploads', 'customers');
и передаю его в свое представление, где я пытаюсь показать каждому клиенту соответствующее имя типа:
@foreach ($inspection->customers as $customer)
{{ $customer->customerTypes->name }}
{{ $customer->first_name . ' ' . $customer->last_name }}
@if ($customer->phone_number_1)
{{ $customer->phone_number_1 }}
@endif
@if ($customer->phone_number_2)
{{ $customer->phone_number_2 }}
@endif
@if ($customer->email_1)
{{ $customer->email_1 }}
@endif
@if ($customer->email_2)
{{ $customer->email_2 }}
@endif
Lifetime Value: ${{ $customer->lifetime_value }}
@endforeach
Здесь я застрял... в настоящее время я получаю следующую ошибку:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'inspection_customers_types.customer_type_id' in 'field list'
Но я нигде не вижу, чтобы я вызывал customer_type_id, поэтому понятия не имею, почему это выдает мне эту ошибку. Вот оператор SQL, который он выдает, если это кому-нибудь поможет:
SELECT
`customer_types`.*,
`inspection_customers_types`.`customer_id` AS `pivot_customer_id`,
`inspection_customers_types`.`customer_type_id` AS `pivot_customer_type_id`,
`inspection_customers_types`.`inspection_id` AS `pivot_inspection_id`,
`inspection_customers_types`.`created_at` AS `pivot_created_at`,
`inspection_customers_types`.`updated_at` AS `pivot_updated_at`
FROM
`customer_types`
INNER JOIN `inspection_customers_types` ON `customer_types`.`id` = `inspection_customers_types`.`customer_type_id`
WHERE
`inspection_customers_types`.`customer_id` = 1
Подробнее здесь: https://stackoverflow.com/questions/782 ... ny-to-many
Мобильная версия