首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在laravel模型中,$this->Products()和$this->Products ()有什么区别?

在laravel模型中,$this->Products()和$this->Products ()有什么区别?
EN

Stack Overflow用户
提问于 2021-09-08 11:16:35
回答 2查看 70关注 0票数 1

我得到了与getReward1getReward2不同的结果

模型

代码语言:javascript
复制
class User extends Authenticatable
{
    public function Products()
    {
        return $this->hasMany('App\Product', 'user_id');
    }

    public function getReward1()
    {
        return $this
        ->Products
        ->where('reward', '>', 0)
        ->where('status', 0)
        ->sum('reward'); // sum = 7,690,000
    }

    public function getReward2()
    {
        return $this
        ->Products()
        ->where('reward', '>', 0)
        ->where('status', 0)
        ->sum('reward'); // sum = 7,470,000
    }
}

getReward1返回7,690,000,getReward2返回7,470,000 (两个不同的值)

$this->Products$this->Products()有什么区别?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-09-08 11:22:46

代码语言:javascript
复制
$this->products; 
// Returns a Collection

$this->products(); 
// Returns a Relation instance, which is a query builder and can be of type HasMany, BelongsTo...

$this->products()->get(); 
// Is EXACTLY like doing $this->products for the first time. 

主要区别在于,products()只是一个尚未执行的查询,而products是该查询的实际结果。

老实说,即使名字是一样的,而且可能令人困惑,它们之间也没有其他相似之处。

一个简单的类比:

代码语言:javascript
复制
DB::table('products')->where('user_id', 18); //could be the $user->products()

DB::table('products')->where('user_id', 18)->get(); //could be $user->products

这只是一个类比,它不完全是这样的内部,但你明白重点。

为了在此基础上增加更多的混乱,Collection方法通常与查询中的方法相似;它们都有where()first().

主要要记住的是,使用括号,您仍然在构建一个查询。在调用getfirst之前,您将一直保留在查询生成器中。

如果没有,您已经有了结果,您是在一个集合(https://laravel.com/docs/8.x/collections)中。

关于getReward1getReward2之间的区别,很难在没有看到数据库结构的情况下准确地知道发生了什么。

这可能是很多事情,但是当您调用sum方法时,您是在getReward1中的集合实例上调用它,在getReward2中调用查询生成器(实际上是用SELECT SUM(reward)...执行查询)。

票数 4
EN

Stack Overflow用户

发布于 2021-09-08 11:23:39

$this->Products()将返回查询生成器的一个实例。子序列where子句将约束DB查询,然后只返回所需的产品。它们将不会存储在模型实例中。

$this->Products将从DB中获取所有产品,并将它们存储在模型实例中,作为一个雄辩的集合。随后的where子句将在雄辩集上执行。

本质上,该方法是在DB中执行所有操作,而属性是获取所有行,然后使用PHP限制它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69102021

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档