I am setting up several Models an want to know the correct approach to table structure and Model relationships.
Let's assume we have a shop containing products, each with properties size and color.
Table products
- id
- size_id
- color_id
- price
Table sizes
- id
- name
Table colors
- id
- name
Models
class Product extends Eloquent {
public function size() {
return $this->hasOne('Size', 'id');
}
public function color() {
return $this->hasOne('Color', 'id');
}
}
class Size extends Eloquent {
public function products() {
return $this->belongsTo('Product', 'size_id');
}
}
class Color extends Eloquent {
public function products() {
return $this->belongsTo('Product', 'color_id');
}
}
This way I can easily echo the color/size of a product using {{ Product->size['name'] }}
. Also, I want to pass Eloquent the size's foreign key size.id
like Product::where('size_id', '5')
rather than its name size.name
.
Problem: Doing $products = Product::has('size', '=', '5')->get()
does not give me any results, yet doing $products = Product::where('size_id', '5')->get()
does.
I am pretty confused, what went wrong?