仅当关系查询计数大于 0 时,我才有获取数据的问题。
这是我的客户关系模型
class Customer extends Model
{
protected $table = 'customers';
public function contracts()
{
return $this->hasMany('App\Contract');
}
这是我的合同模型
class Contract extends Model
{
public function customer()
{
return $this->belongsTo('App\Customer');
}
}
最后,我只需要在某个日期与他们签约的客户
$customers = Customer::with(['contracts' => function($query)
{
$query->where('data_end','>=','2017-07-01')
->where('data_end','<=','2017-07-31')
->where('typ','=','U') ;
}
])->paginate(10);
但我有所有的客户。它看起来像这样:
"Customer 1"
"Customer 2"
"Customer 3"
*"Contract 1"
*"Contract 2"
*"Contract 3"
"Customer 4"
*"Contract 1"
*"Contract 2"
*"Contract 3"
"Customer 4"
在此示例中,我不需要客户 1,2 和 5。我如何通过急切加载和最后的关系对象来做到这一点。
发生这种情况,我不需要屏幕截图上带有 X 的客户 - 我的意思是,我不需要来自哪里查询的 0 个合同的客户
-- 来自 dd() 的对象--
此查询结束 2 个客户,第一个有 2 个合同,第二个有 0 个合同
LengthAwarePaginator {#217 ▼
#total: 75000
#lastPage: 37500
#items: Collection {#213 ▼
#items: array:2 [▼
0 => Customer {#220 ▼
#table: "customers"
#connection: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:5 [▼
"id" => 1
"customer_number" => "46071600600"
"name" => "Nikodem Zalewski"
"customer_contact" => "507614445"
"customer_type" => "P"
]
#original: array:5 [▶]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: array:1 [▼
"contracts" => Collection {#224 ▼
#items: array:2 [▼
0 => Contract {#227 ▼
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:10 [▶]
#original: array:10 [▶]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
1 => Contract {#229 ▶}
]
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
1 => Customer {#221 ▼
#table: "customers"
#connection: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:5 [▶]
#original: array:5 [▼
"id" => 2
"customer_number" => "81050371854"
"name" => "Adam Wróbel"
"customer_contact" => "560047958"
"customer_type" => "P"
]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: array:1 [▼
"contracts" => Collection {#222 ▼
#items: []
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
]
}
#perPage: 2
#currentPage: 1
#path: "*"
#query: []
#fragment: null
#pageName: "page"
}