简体   繁体   中英

Laravel 5 Nested Relationships

I have the following table I can't use Order hasMany Product b/c Product don't have a foreign order_id. I want to access everything through Invoice, is that possible?

I try to use Has Many Through but that is a A->B->C Relationship, I think want I setup need A->B<-C Relationship.

users table

|  id  |

invoice table

|  id  |  user_id  | 

order table

|  id  |  invoice_id  |  product_id  | 

product table

|  id  |  

I wish to access all data through invoice table

INVOICE MODEL

class invoice extends Model {
    public function user() {  
         return $this->belongsTo('App\User');
    }
    public function order() {
         return $this->belongsTo('App\Order');
    }
}

ORDER MODEL

class Order extends Model 
{
    public function invoice()
    {
        return $this->belongsTo('App\Invoice');
    }
}

PRODUCT MODEL

class product extends Model
{
    protected $table = 'products';

    public function order()
    {
        return $this->belongsTo('App\Order');
    }
}

This is how your models should look like according to the schema.

INVOICE MODEL

class invoice extends Model {
    public function user() {  
         return $this->belongsTo('App\User');
    }
    public function order() {
         return $this->hasMany('App\Order');
    }
    public function products() {
         return $this->belongsToMany('App\Product', 'order', 'invoice_id', 'product_id');
    }
}

ORDER MODEL

class Order extends Model 
{
    public function invoice()
    {
        return $this->belongsTo('App\Invoice');
    }
    public function product()
    {
        return $this->belongsTo('App\Product');
    }
}

PRODUCT MODEL

class product extends Model
{
    protected $table = 'products';

    public function orders()
    {
    public function products() {
         return $this->belongsToMany('App\Invoice', 'order', 'product_id', 'invoice_id');
    }
}

If this is not what you want, you will probably need to change the schema.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM