繁体   English   中英

Laravel 调用成员 function addEagerConstraints() on float

[英]Laravel call to a member function addEagerConstraints() on float

我正在尝试获取关系 model 中的列总和,但我收到此错误

在浮动上调用成员 function addEagerConstraints()

代码

model

public function cableLentgh()
{
    return $this->links()->sum('cable_length');
}

逻辑

  1. 我的 model 与这样的link model 有关系
public function links() { return $this->hasManyThrough(Link::class, Segment::class, 'hthree_id', 'segment_id'); }
  1. links表中,我有一个名为cable_length的列,其中存储了数字
  2. 现在我想要这些数字的总和。

任何想法?

更新

完整的错误细节

exception: "Error"
file: "C:\laragon\www\web\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Builder.php"
line: 578
message: "Call to a member function addEagerConstraints() on float"

如果您的关系正确,那么您应该通过以下调用获取链接collection

$this->link

如果返回 collections,则可以运行sum收集方法,如下所示:

public function cableLentgh()
{
    return $this->links->sum('cable_length'); //Notice () removed
}

我知道这可能不是您问题的确切答案,因为您正试图通过查询获得sum ,这是更好的选择。 由于它不起作用,因此使用collection也是一个可以解决您问题的选项。

对我来说,您应该使用变量,而不是 function link

public function cableLentgh()
{
    return $this->links->sum('cable_length');
}

我认为这与关系 ID 有关,我会尝试在 hasManyThrough 文档中指定

class Country extends Model
{
    public function posts()
    {
        return $this->hasManyThrough(
            'App\Post',
            'App\User',
            'country_id', // Foreign key on users table...
            'user_id', // Foreign key on posts table...
            'id', // Local key on countries table...
            'id' // Local key on users table...
        );
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM