我有三个表,结算表有许多添加成员表,密码表有许多添加成员表。在结算和密码模型中,我将函数设置为:
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在ciphers表中。如果我通过AddMember模型处理belongsTo关系,我会得到错误:
(2/2)QueryException 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();
您是否尝试过这种方式,以便雄辩地知道哪个列在哪个表中?
$users = App\User::with(['posts' => function ($query) {
$query->where('title', 'like', '%first%');
}])->get();
或键入有关列的其他Info,如下所示:
App\Book::with('author:id,name')->get();
更多信息请访问laravel文档