Find element of the intermediate table using Laravel

Asked

Viewed 256 times

0

I’m developing a system that has an N:N relationship situation and need to create a third table. The relationship is between Product and Coloured. inside the Product Model, I put this function:

public function colors()
{
 return $this->belongsToMany('App\Color', 'product_colors', 'product_id', 'color_id')
 ->withPivot('price', 'id');
}

Now I needed to access a middle element of the table without giving a foreach. How should I do this query?

  • is this what you seek ? $product->colors()->findOrFail(1, ['product_color_id']);

  • foreach ($product->Colors() as $color) { echo $color->pivot->price; }

  • I wish I didn’t have to use the foreach Jorge Costa.

  • findOrFail will not function pq it will not fetch from the intermediate table, but from the linked table

1 answer

0


When making an inquiry you can use relationship in the following way:

Model::with('colors')->get();

with pulls the function that you created in the Model that you used belongsToMany, if you know what use get() is to pull all the data, but if you want to do a Where in the relationship follow the code:

Model::with('colors')->whereHas('colors', function($query) use ($nome){
   $query->where('nome', $nome);
})->first();

In the example above I asked for the first record, I hope you understood.

Browser other questions tagged

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