问题描述
我有一个简单的问题,但在互联网上找不到任何答案.
I have a simple questions but I cant find any answer in internet.
class Product extends Model
{
use HasFactory;
public function variants()
{
return $this->hasMany(Variant::class);
}
}
>>> $p->variants();
=> Illuminate\Database\Eloquent\Relations\HasMany {#4331}
>>> $p->variants;
=> Illuminate\Database\Eloquent\Collection {#4310
all: [
App\Models\Variant {#4319
id: "1",
name: "VariantOne",
created_at: null,
updated_at: null,
quantity: "2",
product_id: "1",
},
],
}
为什么当我使用方法 variants()
时,我得到了空的 HasMany
对象,但是当我只使用一个 variants
属性时,我得到了一个Collection
有正确的数据?
Why while I'm using method variants()
I got empty HasMany
object but when I use just a variants
property, I got a Collection
with properly data?
variants
属性是如何出现的?我的 Product
类中没有定义它.
And how did variants
property comes up to live? I don't have it defined in my Product
class.
推荐答案
查看文档.它解释了如何将 Eloquent 的关系用于此特定目的.它详细介绍了此处
Take a look at the docs. It explains how you can use Eloquent's relations for this particular purpose. It explains more about the dynamic property given here
这是为了能够完美地查询关系,同时也能够快速接收它们.
This is designed to flawlessly be able to query on relationships, while also being able to quickly receive them.
正如你自己所说:
variants()
返回hasMany
关系,它只是对查询Builder
的附加.当您想进一步查询此关系时,可以使用它:Product::find(1)->variants()->where('quantity', '>', 0)->get()
variants
返回Collection
实例,就像你已经完成variants()->get()
一样,除了你可以继续从Product
Model
访问这个Collection
,它不会从数据库中重新调用它们.对此进行查询时,您将查询Collection
,而不是查询Builder
.
variants()
returns thehasMany
relation, which is just an addition on the queryBuilder
. You use this when you want to query further on this relation:Product::find(1)->variants()->where('quantity', '>', 0)->get()
variants
returns theCollection
instance just like if you had donevariants()->get()
, except you can continue to access thisCollection
from theProduct
Model
, it won't re-call them from the database. When querying on this, you'll be querying on theCollection
, not the queryBuilder
.
这篇关于Laravel Eloquent - 关系方法返回 HasMany 对象,属性返回 Collection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!