【问题标题】:Assigning number of rows of one table to column of another将一个表的行数分配给另一个表的列
【发布时间】:2018-04-03 21:07:13
【问题描述】:

我的情况:我有一张名为“staff”的表,其中包含各种成员。除此之外,我还有另一个名为“children”的表,其中包含成员的孩子(带有外键“staff_id”)。

现在:如何在我的员工表中添加一个名为“number_of_children”的列,其中包含“孩子”表中的条目数,其中“staff_id”是我的员工编号?

附加:在儿童表中,我有一列“考虑”。我只想考虑考虑设置为 true 的条目。有没有办法将它也包含在模型的功能中?会很棒!

谢谢!

【问题讨论】:

  • 请把你的代码放在你目前尝试过的地方。

标签: php mysql laravel eloquent


【解决方案1】:

您需要员工和孩子之间的关系

class Staff extends Model
{
    public function children()
    {
        return $this->hasMany(App\Children::class);
    }
}

那么,就可以这样查询孩子了

$numberOfChildren = $staffMember->children()->count();

More information here.

【讨论】:

  • 感谢美丽的解决方案!我扩展了上面的问题,您也可以回答附加问题吗?
  • 这是childs查询的一个简单的where条件。 $numberOfChildren = $staffMember->children()->where('consider', true)->count()
  • 哦,对了,用了几次。今天不是我的日子。谢谢!
【解决方案2】:

为什么有一个专门的列而不是动态计算呢?这样您就不必担心每次都更新它等。

在您的 staff 模型上,只需为 children 模型添加 hasMany() 关系。

//Staff Model
public function children()
{
    return $this->hasMany('App\Children'); //Substitute Children for the actual name of the model
}

然后您可以随时使用$staff->children->count() 获取孩子。

【讨论】:

  • 感谢美丽的解决方案!我扩展了上面的问题,您也可以回答附加问题吗?
猜你喜欢
  • 2012-06-24
  • 2017-10-29
  • 1970-01-01
  • 2019-07-01
  • 2019-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多