laravel与计数器更改关系结果

2lpgd968  于 2023-01-31  发布在  其他
关注(0)|答案(2)|浏览(85)

我正在尝试使用作用域对关系的筛选部分进行计数

Parent::
withWhereHas('children')
->withCount(['children', function (Builder $builder) {
  $builder->where('status', 1);
}])
->get()

父节点有36个子节点,其中6个状态为1,添加的变量正确,i检索childens_count = 6。
但是我只检索了关系数组中的6个孩子,而我没有限定withWhereHas的作用域,所以我想我遗漏了一些东西。withCount对整个请求有任何副作用吗?在文档中没有看到这一点。
以下是模型中的关系:

// Programme Model
public function childrens(): HasMany
{
  return $this->hasMany(Children::class);
}

// Children Model
public function parent(): BelongsTo
{
    return $this->belongsTo(Parent::class);
}

任何建议都很感谢!

mspsb9vt

mspsb9vt1#

从我对您的问题的理解来看,这就是您需要用来检索所有36个孩子的查询

$parents = Parent::with('children')->get();

如果你想给孩子们的关系设定一个条件

$parents = Parent::withWhereHas('children', fn($q) => $q->where('status', 1))->get();

// notice i use here foreach looping , because get will return a colletion
foreach ($parents as $parent) {
    // to count the children after this query
    count($parent->children); // should return 36
}

如果你想返回两个孩子和一个父节点的计数器

$parent = Parent::query()
   ->withCount('children')
   ->with('children')
   ->where('id', 20) // optional , but best to filter which parent
   ->first(); // this will return a single

// to access how many children
$parent->children_count;

// to access each children 
foreach ($parent->children as $child) {
   // do something here
}

如果你只想计算所有的孩子,我建议你使用孩子。

$children_count = Children::count(); // add filter when needed
    • 编辑:**

为了获取所有的孩子,并且在同一个查询中显示有多少孩子处于活动状态(1),您可以将您雄辩的查询调整为:

// I grab only the first Parent with id 1
$parent = Parent::query()
   ->withWhereHas('children')
   ->withCount(['children' => fn ($q) => $q->where('status', 1)])
   ->where('id', 1)
   ->first();

// this will return all children with any kind of status 
$this->assertTrue( $parent->children->count() === 36 );

// this will return counted children with only status active (1)
$this->assertTrue( $parent->children_count === 6 );
    • 注:**我已经在我当地的测试区测试过了,工作完美。

这里唯一的区别是在开始使用query(),当然还有额外的where(),并且只返回第一个Parent。
希望这能帮到你。

pgvzfuti

pgvzfuti2#

将此关系添加到父类

public function all_children(){
  return $this->hasMany(Parent::class, 'parent_id', 'id');
}
public function active_children(){
  return $this->hasMany(Parent::class, 'parent_id', 'id')
   ->where('status',1);
}

public function inactive_children(){
  return $this->hasMany(Parent::class, 'parent_id', 'id')
  ->where('status',0);
}

那么

Parent::withCount('active_children')->get();

相关问题