Reputation: 2275
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');
}
}
Upvotes: 1
Views: 1720
Reputation: 817
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.
Upvotes: 1