w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Eloquent ORM - How to handle relationships with two instances of the same child model in parent model

What you should have is:

Database Strucuture

Journey
---------
id
origin_id
destionation_id
user_id
date

Address
---------
id
street
city
zipcode

Then, link your Journey model to Address using a One-to-Many relationship:

Journey.php

class Journey extends Model {
    // ...

    public function origin() {
        return $this->belongsTo('Address');
    }

    public function destination() {
        return $this->belongsTo('Address');
    }
}

Address.php

class Address extends Model {
    // ...

    public function journeysAsOrigin() {
        return $this->hasMany('Journey', 'origin_id');
    }

    public function journeysAsDestination() {
        return $this->hasMany('Journey', 'destination_id');
    }
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.