php - Laravel:通过两个模型进行计数

标签 php mysql laravel eloquent

我有三个表,结算表有许多 add_members 表,密码表有许多 add_members 表。在结算和密码模型中我放置了函数:

public function members()
    {
        return $this->hasMany('App\AddMember');
    }

现在,当我需要计算 add_members 表中有多少行但在结算表中使用 reon_id 时,我这样做了:

$first_count = Settlement::where('town_id', Auth::user()->town_id)
  ->with('members')
  ->where('reon_id', '1')
  ->count();

并且该工作正常,但现在我需要第二次计数,它还对结算表中 reon_id == 1 的 add_members 行进行计数,但在密码表中还有一个 cipher == 0 的关系。如果我通过 AddMember 模型处理 ownTo 关系,我会收到错误:

(2/2) 查询异常 SQLSTATE[42S22]:未找到列:1054“where 子句”中的未知列“reon_id”

$second_count = Settlement::where('town_id', Auth::user()->town_id)
      ->with('members')
      ->where('reon_id', '1')
      ->Cipher::with('members')
      ->where('cipher', '0')
      ->count();

我知道这一秒是错误的,但我不知道在结算模型中使用 reon_id == 1 和在密码模型中使用 cipher == 0 很热...

最佳答案

Laravel关系表查询

$first_count = Settlement::where('town_id', Auth::user()->town_id)
  ->with(['members', function ($q) {
        $q->where('reon_id', 1);
}])->get();

$first_count = Settlement::with('members')->where('town_id', Auth::user()->town_id)
  ->whereHas('members', function ($q) {
        $q->where('reon_id', 1);
})->get();

关于php - Laravel:通过两个模型进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47924931/

相关文章:

javascript - 在普通表单提交上加载 GIF

python - 如果数据库(例如 MySQL)中的任何数据更新,是否可以触发脚本或程序?

mysql - 用于大规模更新 MySQL 表的最佳表引擎。 MyISAM 还是 HEAP?

php - 如何在 laravel 中使用一个选择选项发送多个数据?

php - 从 MySQL 数据库中选择正确的选择选项

php - 基准测试 PHP 页面加载时间

mysql - 如何将任意表列名作为记录插入到另一个表中?

php - Laravel 4 分页计数

php - Laravel 不会链接样式表

php - 合并 2 个 SQL "Complex"查询