问题描述
我正在设置几个模型,想知道表结构和模型关系的正确方法。
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
- id
- size_id
- color_id
- price
表尺寸
Table sizes
- id
- 名称
表颜色
Table colors
- id
-
- 名称
模型
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');
}
}
这样我可以很容易地回应颜色/使用 {{Product-> size ['name']}}
的产品。另外,我想通过Eloquent的大小的外键 size.id
像 Product :: where('size_id','5')
而不是其名称 size.name
。
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
.
问题: $ products = Product :: has('size','=','5') - > get()
不给我任何结果, c $ c> $ products = Product :: where('size_id','5') - > get()。
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?
推荐答案
我认为问题是你的 has()
方法正在寻找每个特定产品上具有5种不同大小的产品,这将假设您将使用 $ this-> hasMany('Size')
在您的产品型号。在那里, :: where()
方法返回结果,其中产品的大小为5。
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.
他们使用文档的一个示例的注释。一个帖子将有一个注释列表。你可以找到至少有一个注释的帖子(即 Post :: has('comments') - > get()
)或者你可以找到有更多的帖子超过3条评论(即 Post :: has('comments','> =','3') - > get()
)
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()
).
这篇关于Laravel 4雄辩/模特关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!