我有三个表,结算表有许多 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/