如何从 laravel 中的数据透视表 table 获取更多行

How to fetch more row from a pivot table in laravel

您好,我正在尝试构建一个应用程序,其中有 parent 个元素,每个元素有 children,每个 child 都有自己的子 child。我有一个枢轴 table,它由 user_id、plan_id 和 child_id 组成,现在我正在尝试获取 child。如何获取数组中的所有 children。:

我正在尝试以下代码:

$user = Auth::user();
$selectplan = 1;
$children = $user->relations()->wherePlanId($selectplan)->first()->pivot->child;

我只能获取第一个 child,但我还有更多行要获取:

/**** Table Column ****
*
*
/--id----user_id----plan_id----child----created_at----updated_at
    1        1         1         2        NULL          NULL
    1        1         2         3        NULL          NULL
    1        1         1         4        NULL          NULL
    1        2         1         7        NULL          NULL
    1        2         1         8        NULL          NULL
    1        2         3         10       NULL          NULL

请帮帮我。谢谢!

first 只有 return 一个模型实例;第一个匹配查询约束。为了 return 一个集合你需要使用 get

$children = $user->relations()->wherePlanId($selectplan)->get()->pivot->child;