//客户端模型

protected $fillable = [
        'client_name', 'plan_id', 'client_type'
    ];

public function plan(){
        return $this->belongsTo(Plan::class, 'plan_id', 'id');
    }


//计划模型

protected $fillable = [
        'price'
    ];

public function clients()
    {
        return $this->hasMany(Client::class);
    }


我想获得其中client_type =某物的所有客户的总价

最佳答案

我会这样做:

function getClientTypeTotal($clientType)
{
    return Client::where('client_type', $clientType)->get()->sum(function ($client) {
        return $client->plan->price;
    })
}

关于mysql - 如何从laravel的关系中获得和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55222300/

10-11 05:37