【问题标题】:I want to remove certain data on pivot table from my JSON output Laravel我想从我的 JSON 输出 Laravel 中删除数据透视表上的某些数据
【发布时间】:2022-01-23 12:46:37
【问题描述】:

我有两个数据库表:练习和时间表。它们之间的关系是多对多的。 我有一些数据存储在数据透视表中。当我返回表格时,我不希望显示 id,因为它是无用的重复。我正在使用的代码:

$results =  Schedule::with(['exercises', 'exercises.tags'])->where('user_id', Auth::user()->id)
            ->get();
        $results->each(function ($schedule) {
            $schedule->exercises->each->makeVisible('pivot');
        });

我尝试了这种方法,但它似乎不起作用:

$results = $results->toArray();
        foreach ($results as $schedule) {
            foreach ($schedule['exercises'] as $exercise) {
                unset($exercise['pivot']['schedule_id']);
                unset($exercise['pivot']['exercise_id']);
            }
        }

我知道这个问题可能不太清楚,很抱歉,但我的英语不是最好的。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    使用雄辩的ma​​keHidden方法:

    $results = $results ->makeHidden(['exercises.pivot.schedule_id']);
    

    来源:https://laravel.com/docs/8.x/eloquent-collections#method-makeHidden

    【讨论】:

    • 它不起作用。我忘记了一个细节:pivot 字段默认是隐藏的,所以我必须让它可见,然后隐藏 schedule_id 和 exercise_id,但它不起作用。
    • @giuszeppe 我不明白......你说你试图从默认隐藏的输出中删除数据透视字段,所以你到底想做什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    相关资源
    最近更新 更多