1

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?

Nyxynyx
  • 61,411
  • 155
  • 482
  • 830

1 Answers1

4

I think that the problem is that your ::has() method is looking for products with exactly 5 different sizes on each specific product, which would assume that you would be using $this->hasMany('Size') in your Product model. Where as the ::where() method is returning results where the size of the product is 5.

In the documentation they use an example of comments. A post will have a list of comments. You can find posts that have at least one comment (ie. Post::has('comments')->get()) or you can find posts that have more than 3 comments (ie. Post::has('comments', '>=', '3')->get()).

http://laravel.com/docs/eloquent#querying-relations

andersryanc
  • 939
  • 7
  • 19