Ad

Laravel 5.7 Many To Many With Custome Table Name

- 1 answer

Goods Model

class goods extends Model
{
  protected $table = "goods";
  public function sales(){
    return $this->belongsToMany('App\sales', 'sales_details', 'goods', 'sales');
  }
}

Sales Model

class sales extends Model
{
  protected $table = "sales";
  public function goods(){
    return $this->belongsToMany('App\goods','sales_details','sales','goods');
  }
}

i also make this model but i don't know if i ever need it or not

class salesDetail extends Model
    {
      protected $table = "sales_details";
    }

my controller

public function test()
    {
      $goods = goods::all();
      return view('test',compact('goods'));
    }

my test.blade.php

@foreach($goods as $data)
    <li><strong>{{ $data->name }}</strong> - {{ $data->company->kind }} {{ $data->company->name }}</li>
    <p>{{ $goods->sales }}</p>
  @endforeach

i connect goods table with sales table with many to many without following laravel naming. This is my table contents

goods
-id
-name

sales
-id
-date

sales_details
-goods
-sales
-qty
-price

and i couldn't make it work. i just wanted to show the result like this

sales -id
sales - date
goods - name
sales_details - qty
sales_details - price

this should be the result this should be the result

Ad

Answer

In your @foreach loop you're trying to access sales on the collection of goods rather than the instance in the loop. Also, because the sales() relationship is a belongsToMany (many-to-many) you're going to get a collection and not a single instance so you're going to need to loop through them as well e.g.

@foreach($goods as $data)
    <li>
        <strong>{{ $data->name }}</strong> - {{ $data->company->kind }} {{ $data->company->name }}

        @foreach($data->sales as $sale)
            <p>{{ $sale->date }} - {{ $sale->pivot->qty }}</p>
        @endforeach
    </li>
@endforeach

To access data from your pivot table you will first need to tell Laravel to include that information in the relationship:

public function sales()
{
    return $this->belongsToMany('App\sales', 'sales_details', 'goods', 'sales')
        ->withPivot('qty', 'price');
}

You should also add the withPivot method to the good() relationship in the sales class as well.

Then you'll be able access the information from the pivot property. This is happening in the example above with {{ $sale->pivot->qty }}.

Many to many docs (scroll down to Retrieving Intermediate Table Columns )

Ad
source: stackoverflow.com
Ad