簡體   English   中英

將一個表的行數分配給另一個表的列

[英]Assigning number of rows of one table to column of another

我的情況:我有一個名為“ staff”的表,其中包含各種成員。 在此旁邊,我還有另一個名為“ children”的表,其中包含成員的孩子(外鍵為“ staff_id”)。

現在:如何在工作人員表中添加一個名為“ number_of_children”的列,其中包含“ children”表中的條目數,其中“ staff_id”是我的staffid?

另外:在子表中,我有一列“考慮”。 我只想考慮將“考慮”設置為true的條目。 有沒有辦法將其包含在模型的功能中? 會很好!

謝謝!

您需要員工與孩子之間的關系

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

然后,您可以像這樣查詢孩子

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

更多信息在這里。

為什么要為此設置專用列而不是僅動態地計算呢? 這樣,您就不必擔心每次都更新它了。

在您的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()獲取孩子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM