0
votes

I have the following relation:

  1. RAB hasMany products.
  2. products belongsToMany RAB

but this products also hasMany currency that belongsToOne RAB itself. it looks like this.

table

in RAB model:

  public function products()
    {
        return $this->belongsToMany('App\ModelKeuangan\ProductsModel', 'rab_products', 'rab_id', 'products_id');
    }

in products model:

public function rab()
    {
        return $this->belongsToMany('App\ModelUnitKerja\Perencanaan\RabModel', 'rab_products', 'products_id', 'rab_id');
    }

rab_products is my intermediate/join table.

it works just fine when im syncing products data for RAB. but i cant get how to make eloquent model for syncing Currency data to rab and products.

do i need to make model for currency too? if yes, how do i define it?

my plan is make a pivot like this, but can i make relation inside pivot table?

class RabProducts extends Pivot {
    //relation function to currency
}

and change my products model something like:

   public function rab(){
       return $this->belongsToMany('App\ModelUnitKerja\Perencanaan\RabModel')->using('App\RabProducts');
}
1
You have to create model for every table except the pivot ones. If currencies is a table, you have to create a model - alberto-bottarini

1 Answers

0
votes
  1. Create the currency model and add foreign_key product_id:
php artisan make:model Currency
  1. Build the one-to-many between Product and Currency and you need to add product_id in your currencies table.

In your Currency Model:

    public function product() {
      return $this->belongsTo('App\Product', 'product_id');
    }

In your Product Model:

    public function currencies()
    {
        return $this->hasMany(\App\Currency::class, 'product_id', 'id');
    }

So that you can call it like this:

RAB::with(['products' => function($query) {
    $query->with('currencies');
}])->get();

Unfortunately, the foreign_key between products and rabs is in pivot table, you cannot create the hasmanythrough with currency directly.

You can call the currency by products. Or you can create a pivot model, and then use hasmanythrough.