Home > other >  How to get related data from the pivot table?
How to get related data from the pivot table?

Time:08-19

I have the following data model

Quotes
*id
*description
*total
*net
*vat

Quote Details
*id
*product_id
*quote_id
*quantity
*unit_price
*discount

Products
*id
*name
*stock
*price

And I need to fill the detail of the invoice for that I wanted to do it with laravel eloquent relations, which I did the following query:

Controller

$prod = Quote::find($quote->implode('id'));
$details = QuotationDetail::whereQuote($quote->implode('id'))->get();

// Here I want to get the product code and the product name from Quotation_details. But it doesn't let me do it with relations.

The belongsToMany relations work, but if I want to make relation from QuotationDetails to Products it doesn't work for me.

Models

Quote
    public function products()
    {
        return $this->belongsToMany(Product::class,'quotation_details')->selectRaw('code,name,quantity,discount,quotation_details.unit_price as price_quote')->withTimestamps();
    }

QuotationDetails
    public function quotes()
    {
        return $this->belongsToMany(Quote::class, 'quotation_details'); //Worked
    }

    public function products(){
        return $this->belongsTo(Product::class); // Not work
    }

Products
    public function quotes()
    {
        return $this->belongsToMany(Quote::class,'quotation_details');
    }

CodePudding user response:

I think QuotationDetail model should be modified:

public function quote()
{
    return $this->belongsTo(Quote::class, 'quote_id', 'id');
}

public function product()
{
    return $this->belongsTo(Product::class, 'product_id', 'id');
}
$details = QuotationDetail::with('quote', 'product')
           ->whereHas('product', function ($q) use ($request) {
               $q->where('name_of_product_table.column' , $request->param);
           )
           ->get();
foreach ($details as $detail) {
   dd($detail->product);
}
  • Related