0

Distributor Table - id Product Table - id Distributorprocuct Table - distributor_id, product_id

Distributor Model -

public function product() { return $this->hasMany(Distributorproduct::class); }

Product Model -

public function distributor() { return $this->hasMany(Distributorproduct::class); }

Distributorproduct Model -

public function distributor() { return $this->belongsTo(Distributor::class); }

public function product() { return $this->belongsTo(Product::class); }

If I write $product->distributor then it gives me all the details of distributorproduct but i need the details of distributor not distributorproduct .

If i write $distributor->product then it gives me all the details of distributorproduct but i need the details of product not distributorproduct .

Thanks in advance...

1 Answers1

1

It is not clear to me what is the relationship between Product, DistributorProduct and Distributor, but I think what you want is to specify a different kind of relationship between Distributor and Product (and Product -> Distributor). In your Distributor modal class you can try defining your product method like this:

public function product() { 
    return $this->hasOneThrough(Product::class, Distributorproduct::class); 
}

and the distributor method in the Product modal class like this:

public function distributor() { 
    return $this->hasOneThrough(Distributor::class, Distributorproduct::class); 
}

But your mileage may vary, this kind of relationship is ok only if a Product has a single distributor (likely), and a distributor has a single Product (unlikely I guess).

The Laravel docs have a pretty good documentation about relationships. Looks especially at the Has One Through and the Has Many Through paragraphs.

gere
  • 1,600
  • 1
  • 12
  • 19
  • has one through is a single way relationship if i have tables relationships like distributor->distributorproduct (foreign key distributor_id)->product(foreign key distributorproduct_id) than it works but in my case i cannot store the primary key of distributorproduct_id in product table so if use hasOneThrough generates sql query error.... – Moin Dhatiwala Feb 05 '20 at 12:50