Вставка отношений с таблицей ссылок - PullRequest
0 голосов
/ 03 февраля 2020

У меня есть некоторые проблемы при вставке новой записи с моделью отношений. У меня есть 3 таблицы Contacts, Contact_Customer и Customers. Модели следующие:

Контакт. php

class Contact extends Model
{
    protected $fillable = [
        'FIRST_NAME',
        'INSERTION',
        'LAST_NAME',
        'EMAIL',
        'PHONE_NUMBER',
    ];

   public function contact_customers(){
        return $this->HasMany(Contact_Customer::class, 'CONTACT_ID','ID');
    }
}

Контакт_Клиент. php

class Contact_Customer extends Model
{
    protected $fillable = [
        'CONTACT_ID',
        'CUSTOMER_ID'
    ];

    public function customer()
    {
        return $this->belongsTo(Customer::class, 'ID');
    }

    public function contact(){
        return $this->belongsTo(Contact::class, 'ID');
    }
}

Заказчик. php

class Customer extends Model
{
    protected $fillable = [
        'COMPANY_NAME',
        'ZIPCODE',
        'STREET',
        'HOUSE_NUMBER',
        'CITY',
        'COUNTRY',
    ];

    public function contact_customers(){
        return $this->HasMany(Contact_Customer::class, 'CUSTOMER_ID','ID');
    }

}

Я написал в ContactController функцию для добавления контакта к клиенту с помощью этой функции:

public function create(Request $request, $customer_id)
    {
        $contact = Contact::create([
            'FIRST_NAME' => $request->input('first_name'),
            'INSERTION' => $request->input('insertion'),
            'LAST_NAME' => $request->input('last_name'),
            'EMAIL' => $request->input('email'),
            'PHONE_NUMBER' => $request->input('phone'),
        ]);

        $contact_customer = Contact_Customer::create([
            'CUSTOMER_ID' => $customer_id,
            'CONTACT_ID' => $contact->id
        ]);

        $customer = Customer::find($customer_id);
        $customer->push();

        return redirect('/customer/'.$customer_id.'/show');
    }

Записи будут отправлены в базу данных, но представление дает мне эту ошибку: Попытка получить свойство 'FIRST_NAME' для необъекта (Представление: /home/vagrant/Code/Laravel/resources/views/customer/show.blade.php)

И мой взгляд такой

<h2>Contactpersonen</h2>
        <table class="table table-borderless">
            <tbody>
            @foreach($customer->contact_customers as $contact)
                <tr>
                    <td>{{ $contact->contact->FIRST_NAME }} {{$contact->contact->INSERTION}} {{$contact->contact->LAST_NAME }}</td>
                    <td>{{ $contact->contact->PHONE_NUMBER }}</td>
                    <td>{{ $contact->contact->EMAIL }}</td>
                </tr>
            @endforeach
            </tbody>
        </table>
        <h2>Aanmaken contactpersoon</h2>
        <form method="POST" action="/customer/{{$customer->ID}}/contact/create" id="contactform">
            @csrf
            <div class="form-group">
                <label for="customer">Voornaam</label>
                <input type="text" class="form-control" id="first_name" name="first_name">
            </div>
            <div class="form-group">
                <label for="zipcode">Tussenvoegsel</label>
                <input type="text" class="form-control" id="insertion" name="insertion">
            </div>
            <div class="form-group">
                <label for="street">Achternaam</label>
                <input type="text" class="form-control" id="last_name" name="last_name">
            </div>
            <div class="form-group">
                <label for="house_number">E-mail</label>
                <input type="text" class="form-control" id="email" name="email">
            </div>
            <div class="form-group">
                <label for="country">Mobiel</label>
                <input type="text" class="form-control" id="phone" name="phone">
            </div>
            <button type="submit" class="btn btn-primary">Toevoegen</button>
        </form>

Таким образом, представление не видит новых отношений. Я попытался сделать несколько решений на слабину и прочитал laracast https://laravel.com/docs/5.8/eloquent-relationships#inserting -and-update-related-models . Но я не могу найти решение.

Надеюсь, вы видите мою ошибку, спасибо за чтение.

1 Ответ

0 голосов
/ 03 февраля 2020

попробуйте ниже приведенный код в App \ Contact_Customer. php может быть, ваши отношения не связаны правильно

class Contact_Customer extends Model
{
protected $fillable = [
    'CONTACT_ID',
    'CUSTOMER_ID'
];

 public function customer()
{
    return $this->belongsTo(Customer::class, 'CUSTOMER_ID', 'ID');
}

public function contact(){
    return $this->belongsTo(Contact::class, 'CONTACT_ID', 'ID');
}
}
...