vendredi 25 mars 2016

How to use Laravel's hasManyThrough across 4 tables

I have 4 tables with a structure and flow like this:

User
Accounts
Contacts
Orders

The relationship is as follows:

$user->hasMany('accounts')->hasMany('contacts')->hasMany('orders');

/** User Model **/
class User extend Eloquent {
    public function accounts(){
        return $this->hasMany('Accounts');
    }

    public function contacts(){
        return $this->hasManyThrough('Contact', 'Account', 'owner_id');
    }

    //how do I get this?
    public function orders(){

    }
}

/** Account Model */
class Account extends Eloquent {
    public function $user(){
        return $this->belongsTo('User');
    }
    public function contacts(){
        return $this->hasMany('Contact');
    }
}

/** Contact Model **/
class Contact extends Eloquent {
    public function account(){
        return $this->belongsTo('Account');
    }

    public function orders(){
        return $this->hasMany('Order');
    }
}

/** Order Model **/
class Order extends Eloquent {
    public function contact(){
        return $this->belongsTo('contact');
    }
}

A classic hasManyThrough is not possible because we have 4 tables.

How can I create a relationship so that a single user can have it's orders accessed without method chaining each model, such as:

User::find(8)->orders;



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire