你应该在合约模型上实现关系
// Contract.php
public function signatures() {
// add proper parameters 2nd: foreign key and 3rd: local key if
// your Database design is not respecting laravel/eloquent naming guidelines
return $this->hasMany(Signature::class);
}
为了检索 未签署的合同,这应该可以工作:
$unsignedContracts = Contract::whereHas("signatures", '<', 2)->get();
我认为这也应该完全不包括条目,但如果没有,你也可以试试这个
$unsignedContracts = Contract::whereDoesntHave("signatures")
->orWhereHas("signatures", '<', 2)->get();
如果您想查询所有带有附加条件的签名,这也是可能的:
$unsignedContracts = Contract::whereHas("signatures", function($q) {
$q->where("signed","=",false);
})->get()
您还可以在 Signature 模型中引入承包商和订购者的具体关系:
// Signature.php
public function contractor() {
return $this->belongsTo(User::class, "contractor_user_id", "id");
}
public function orderer() {
return $this->belongsTo(User::class, "orderer_user_id", "id");
}
有了这些你应该可以做到:
// this should return all contracts where one of the
// required users has not signed yet
$unsignedContracts = Contract::where(function($q) {
$q->whereDoesntHave("contractor")
->orWhereDoesntHave("orderer");
})->get();
Laravel 文档非常好,恕我直言,请查看
https://laravel.com/docs/5.6/eloquent-relationships#querying-relations 以获取更多信息。