Laravel-通过所属项目的计数
一家公司可以有许多交货日期。交付日期可能有多个条目。条目模型包含Laravel-通过所属项目的计数,laravel,laravel-5,Laravel,Laravel 5,一家公司可以有许多交货日期。交付日期可能有多个条目。条目模型包含 public function company() { return $this->belongsTo(Company::class); } public function delivery_date() { return $this->belongsTo(MgDeliveryDate::class, 'mg_delivery_date_id'); } 我想要的是每个公司每个交货日期有多少条记录。
public function company()
{
return $this->belongsTo(Company::class);
}
public function delivery_date()
{
return $this->belongsTo(MgDeliveryDate::class, 'mg_delivery_date_id');
}
我想要的是每个公司每个交货日期有多少条记录。比如说
$companies = Company->with('delivery_dates', 'delivery_dates.entries')->withCount('delivery_dates.entries')
所以如果我的数据是
Company Delivery Date Entry Number
A 1/2/2020 1
A 1/2/2020 2
A 2/2/2020 3
B 1/2/2020 4
我会得到两个公司,A公司有两个交付日期,第一个日期(2020年1月2日)计数为2,第二个日期(2020年2月2日)计数为1,B公司有一个交付日期,输入计数为1 好问题。试试看
$companies = Company::with('delivery_dates.entries')->get();
$companies->map(function($company){
return $company->delivery_dates->map(function($delivery){
return $delivery->entries->count();
})->groupBy('delivery_date');
});
我使用了拉威尔收集法。好问题。试试看
$companies = Company::with('delivery_dates.entries')->get();
$companies->map(function($company){
return $company->delivery_dates->map(function($delivery){
return $delivery->entries->count();
})->groupBy('delivery_date');
});
我使用了拉威尔收集方法。//我不确定你到底想要什么。。如果你想要这样的数据,那么你可以试试这个
[
{ company:abc , date:[{1/20} , {2/20} ...] , entry:[{1} ,{2} ...]} ,
{},
....
]
公司模式
public function entry()
{
return $this->hasMany(entry::class);
}
And Then
$companies = Company::withCount(['entry', 'delivery_dates' => function ($query) {
$query->where(your condition);
}])->get();
//我不确定你到底想要什么。。如果你想要这样的数据,那么你可以试试这个
[
{ company:abc , date:[{1/20} , {2/20} ...] , entry:[{1} ,{2} ...]} ,
{},
....
]
公司模式
public function entry()
{
return $this->hasMany(entry::class);
}
And Then
$companies = Company::withCount(['entry', 'delivery_dates' => function ($query) {
$query->where(your condition);
}])->get();
你可以写:
$companies = Compnay::with(['delivery_dates' => function ($q) {
$q->withCount('entries');
}])
->get();
您将得到以下结果:
你可以写:
$companies = Compnay::with(['delivery_dates' => function ($q) {
$q->withCount('entries');
}])
->get();
您将得到以下结果:
您可以加入他们,并按字段分组。您可以加入他们,并按字段分组感谢您的帮助。目前,第一步是错误的。我得到了该公司的所有交货日期,这是正确的,但随后得到了该交货日期的所有条目,而不仅仅是该公司和交货日期的条目。有什么想法吗?谢谢你的帮助。目前,第一步是错误的。我得到了该公司的所有交货日期,这是正确的,但随后得到了该交货日期的所有条目,而不仅仅是该公司和交货日期的条目。有什么想法吗?谢谢Yezan,但这将为我提供该交付日期的所有条目,而不仅仅是该公司的条目。这有意义吗?我不这么认为,一家
公司
有许多交付日期
,而交付日期
有许多条目
。因此,我向您提供的查询将加载公司的交货日期,这些公司的交货日期依次包含该特定公司交货日期的条目计数。谢谢Yezan,但这将为我提供该交货日期的所有条目,而不仅仅是该公司的条目。这有意义吗?我不这么认为,一家公司
有许多交付日期
,而交付日期
有许多条目
。因此,我给您的查询将加载带有交付日期的公司,这些公司的交付日期依次包含该特定公司的交付日期的输入计数。