Sergej Fomin
Sergej Fomin

Reputation: 2002

Laravel One-to-Many and One-To-One relationship between the same tables

I have 2 tables: Tourists, Tours. (and corresponding models Tourist, Tour).

I have successfully set up many-to-many relationship between them. When I

$tour->tourists()->attach($tourist);

It creates a new record in a table Tour_Tourists. (tour_id, tourist_id, created_at, updated_at). It shows which tourists go with the particular tour.

Now I need to create another entity: Buyer. The buyer is one of the Tourists who pays for the Tour. Only one of the tourists belonging to the tour can be a Buyer.

I have set up one-to-one relations in both models:

<?php

namespace App;

class Tour extends Model { public function tourists() {

    return $this->belongsToMany('App\Tourist')
    ->withTimestamps();

}

public function buyer() {

    return $this->hasOne('App\Tourist')
    ->withTimestamps();

}

}

(and the same in Tourist model, except i changed 'App\Tourist' to 'App\Tour':

public function buyer() {

return $this->hasOne('App\Tour')
->withTimestamps();

)

but when I do:

$tour->buyer()->($tourist) 

(where $tour and $tourist contain respective records from database), i get:

BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::withTimestamps()'

I have a feeling that I am doing it totally wrong. Can anyone just point out the direction I should move on to?

thank you.

Upvotes: 0

Views: 1092

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35367

withTimestamps() is a method used for belongsToMany only because it updates the created_at/updated_at fields of the pivot table. hasOne won't have this method.

Upvotes: 1

Related Questions