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');
– Lucas Pace
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.– Fernando Piovezan