Laravel Eloquent - 关系方法返回 HasMany 对象,属性返回 Collection [英] Laravel Eloquent - relations method is returning HasMany object and property is returning Collection

查看:136
本文介绍了Laravel Eloquent - 关系方法返回 HasMany 对象,属性返回 Collection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题,但在互联网上找不到任何答案.

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 the hasMany relation, which is just an addition on the query Builder. You use this when you want to query further on this relation: Product::find(1)->variants()->where('quantity', '>', 0)->get()
  • variants returns the Collection instance just like if you had done variants()->get(), except you can continue to access this Collection from the Product Model, it won't re-call them from the database. When querying on this, you'll be querying on the Collection, not the query Builder.

这篇关于Laravel Eloquent - 关系方法返回 HasMany 对象,属性返回 Collection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆