Reputation: 12327
There are 3 tables
Sizes
id
name
Products
id
name
Product_sizes
id
product_id
size_id
I want to fill an selectbox with the id of product_sizes and the name of the foreign key connected table size.
for exampe:
product_sizes.id 1
sizes.name medium
where medium would be found by size_id in product sizes. How can I the name value in the list?
What i currently have
I can get the right row with
$sizes = $product->sizeAvailable()->lists('pr', 'size_id');
where sizeAvailable is a relation that returns all product_sizes for a selected product.
Upvotes: 0
Views: 570
Reputation: 116
First of all you don't need an id
field in the pivot table because you can uniquely identify each row with the composite key product_id, size_id
. A Product can belong to many Sizes and a Size can belong to many Products, thus you shouldn't have duplicate rows.
The relationships of each model are like the following:
class Product extends Model {
public function sizeAvailable() {
return $this->belongToMany('Size', 'product_sizes');
}
}
class Size extends Model {
public function products() {
return $this->belongToMany('Product', 'product_sizes');
}
}
Finally in your View you can use Blade functions to generate your selectbox:
<select>
@foreach($product->sizeAvailable() as $size)
<option value="{{ $size->id }}">{{ $size->name }}</option>
@endforeach
</select>
Upvotes: 1