我得到了与getReward1和getReward2不同的结果
模型
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()有什么区别?
发布于 2021-09-08 11:22:46
$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是该查询的实际结果。
老实说,即使名字是一样的,而且可能令人困惑,它们之间也没有其他相似之处。
一个简单的类比:
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().
主要要记住的是,使用括号,您仍然在构建一个查询。在调用get或first之前,您将一直保留在查询生成器中。
如果没有,您已经有了结果,您是在一个集合(https://laravel.com/docs/8.x/collections)中。
关于getReward1和getReward2之间的区别,很难在没有看到数据库结构的情况下准确地知道发生了什么。
这可能是很多事情,但是当您调用sum方法时,您是在getReward1中的集合实例上调用它,在getReward2中调用查询生成器(实际上是用SELECT SUM(reward)...执行查询)。
发布于 2021-09-08 11:23:39
$this->Products()将返回查询生成器的一个实例。子序列where子句将约束DB查询,然后只返回所需的产品。它们将不会存储在模型实例中。
$this->Products将从DB中获取所有产品,并将它们存储在模型实例中,作为一个雄辩的集合。随后的where子句将在雄辩集上执行。
本质上,该方法是在DB中执行所有操作,而属性是获取所有行,然后使用PHP限制它。
https://stackoverflow.com/questions/69102021
复制相似问题