Doubt with belongsToMany Standard 7

Asked

Viewed 86 times

0

I have a relationship N:N that’s giving me trouble in returning using the with() follows the example of my two models with problem and the way I call the query.

Model product_type

public function makes()
{
    return $this->belongsToMany(\App\Models\Make::class);
}

Model make

public function productTypes()
{
   return $this->belongsToMany(\App\Models\ProductType::class);
}

My relation table has the following fields

make_product_type -> nome da tabela
make_id
product_type_id

In my controller I am trying to return all products with your brands in this way

Make::with('productTypes')->get()

but at this point the following error is returned:

Trying to get Property 'make_id' of non-object

I have already tried to inform the relationship fields on the model but it also did not work. The only way it worked was by overwriting the model’s toArray() method and forcing the relationship in return, which for me is not feasible since I only need to return this relationship in a query that is executed.

public function toArray()
{
    return [
       'id' => $this->id,
       'name' => $this->name,
       'product_type' => $this->productTypes()->get()->toArray()
     ];
}

If someone can explain to me what I am doing wrong and especially why this wrong would be very grateful, because I have read several times the documentation of Laravel and I have not succeeded in understanding what the problem is. Obs. if there is suggestion of change in the table structure there is also no problem as I am starting a project and at this time I can still change things

  • Have you tried specifying the relation table and fields? This way: Return $this->belongsToMany(\App\Models\ProductType::class, 'product_type_id', 'make_id');

  • I tried it this way return $this->belongsToMany(\App\Models\ProductType::class, 'make_product_type', 'make_id', 'product_type_id'); and the result is the same error I reported above.

1 answer

0

What version does use the Laravel? Made a pivot table in this case of N:N?

Try to do it this way:

Model Make

public function Products(){
    return $this->belongsToMany(Product_type::class);
}

Model Product_type

public function makes(){
    return $this->belongsToMany(Make::class);
}

Pivot table? (In alphabetical order)

public function up()
{
    Schema::create('make_producttype', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('make_id');
        $table->bigInteger('producttype_id');
        $table->timestamps();
    });
}

In View would be so to access.

        @foreach($make->productsas $pro)
             <p class="badge badge-success">{{$pro->name}}</p>
         @endforeach

Browser other questions tagged

You are not signed in. Login or sign up in order to post.