简体   繁体   English

Laravel 4 Eloquent / Model关系

[英]Laravel 4 Eloquent/Model Relationships

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 products

  • id ID
  • size_id size_id
  • color_id COLOR_ID
  • price 价钱

Table sizes sizes

  • id ID
  • name 名称

Table colors colors

  • id 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'] }} . 通过这种方式,我可以使用{{ 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 . 另外,我想传递size.id大小的外键size.idProduct::where('size_id', '5')而不是名称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. 问题:$products = Product::has('size', '=', '5')->get()不给我任何结果,但做$products = Product::where('size_id', '5')->get()

I am pretty confused, what went wrong? 我很困惑,出了什么问题?

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. 我认为问题在于你的::has()方法正在寻找每种特定产品上只有5种不同尺寸的产品,这会假设你在产品模型中使用$this->hasMany('Size') Where as the ::where() method is returning results where the size of the product is 5. 其中::where()方法返回结果,其中产品的大小为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() ). 你可以找到至少有一条评论的Post::has('comments')->get() (即Post::has('comments')->get() ),或者你可以找到评论超过3条的Post::has('comments', '>=', '3')->get() (即Post::has('comments', '>=', '3')->get() )。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM