【问题标题】:What is difference between $this->Products and $this->Products() in laravel model?laravel 模型中的 $this->Products 和 $this->Products() 有什么区别?
【发布时间】:2021-11-05 03:58:35
【问题描述】:

我从getReward1getReward2 得到不同的结果:

型号

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() 有什么区别?

【问题讨论】:

    标签: laravel eloquent model


    【解决方案1】:
    $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()...

    要记住的主要事情是,使用括号,您仍在构建查询。在您调用 getfirst 之前,您仍处于查询构建器中。

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


    关于getReward1getReward2 之间的区别,如果不查看数据库结构,很难准确判断发生了什么。

    可能有很多东西,但是当您调用 sum 方法时,您是在 getReward1 中的 Collection 实例和 getReward2 中的查询构建器上调用它(您实际上是在执行查询SELECT SUM(reward)...)。

    【讨论】:

    • 非常感谢。我认为 return $this->Products->where('reward', '>', 0)->where('status', 0) 并不适用所有 where 条件。而DB::table('products')->where('reward', '>', 0)->where('status', 0)$this->Products()->where()->where() 则返回最正确的结果。
    【解决方案2】:

    $this->Products() 将返回查询生成器的实例。子序列where 子句将约束数据库查询,然后只返回您想要的产品。这些不会存储在模型实例中。

    $this->Products 将从数据库中获取所有产品并将它们作为 Eloquent 集合存储在模型实例中。随后的 where 子句将在 Eloquent 集合上执行。

    本质上,该方法在数据库中执行所有操作,而该属性正在获取所有行,然后使用 PHP 对其进行限制。

    【讨论】:

      猜你喜欢
      • 2010-11-06
      • 2011-04-12
      • 1970-01-01
      • 2011-04-10
      • 2011-06-07
      • 1970-01-01
      • 2013-08-09
      • 1970-01-01
      相关资源
      最近更新 更多