简体   繁体   English

用laravel中的所有可能实例填充数据透视表

[英]fill a pivot table with all possible instances in laravel

I have two tables: days and times . 我有两个表: 天和 时间 These tables have a N:N relationship with each other.So I used a pivot table for them: days_times . 这些表彼此之间具有N:N关系,因此我为其使用了数据透视表: days_times
In my view I need a button when clicked,fills the pivot table with all the possible instances. 在我看来,单击时需要一个按钮,将所有可能的实例填充到数据透视表中。 for example if there are 2 records in days and 2 records in times ,the pivot table after the process should has 4 records: 例如,如果有2名记录在 2对记录在 ,枢轴表的处理之后应具有4个记录:
day_id | time_id
1 | 1
1 | 2
2 | 1
2 | 2

Let's consider an action like ScheduleController@fill wants to take care of this process. 让我们考虑一个类似ScheduleController@fill想要处理这个过程。 How should I achieved this? 我应该如何实现呢?

Here's my answer,I don't know if there is a better solution: 这是我的答案,我不知道是否有更好的解决方案:

public function fill(){
    $days = Day::all();
    foreach($days as $day)
    {
        $times = Time::all();
        foreach($times as $time)
        {
            $day->times()->attach($time->id);
        }
    }
}

I know this is not efficient but at least it works. 我知道这不是很有效,但至少可以奏效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM