如何加入insert语句?

Here is my table structure:

// pages
+----+-----------------------+--------+
| id |         path          | method |
+----+-----------------------+--------+
| 1  | list_role             | get    |
| 2  | make_role             | post   |
| 3  | edit_role/id          | get    |
| 4  | list_voucher/activate | get    |
| 5  | list_voucher/activate | post   |
| 6  | expire_voucher/id     | get    |
+----+-----------------------+--------+

// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+

Now I want to insert multiple rows into role_page table according to this array: (noted that I have $role_id)

$arr = [['list_role', 'get'], ['list_voucher/activate', 'get']]
$role_id = 4; // for example

So the expected output is:

// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+
| 4       | 1       |
| 4       | 4       |
+---------+---------+

How can I do that by a join?


Currently I do that by a loop on $arr like this:

$role_id = 4;

foreach($arr as $row) {
    // match the page id
    $page_id = pages::where('path', row[0])->where('method', row[1])->first();

    // insert
    $role_page = new role_page;
    $role_page->role_id = $role_id;
    $role_page->page_id = $page_id;
}

Try this

Page Model (you may have to customize this relation)

public function roles(){
    return $this->belongsToMany(Role::class, 'role_page', 'page_id', 'role_id')
}

Then

$arr = [['list_role', 'get'], ['list_voucher/activate', 'get']]
$role_id = 4; // for example

$query = Page::query();

foreach ($arr as $page){
    $query = $query->orWhere(function($query){
        $query->where('path', $page[0])->where('method', $page[1]);
    }
}
$pages =$query->get();

foreach($pages as $page){
    $page->roles()->attach($role_id);
}
$page_id = pages::where('path', row[0])->where('method', row[1])->first();

This returns an object.

$page_id = pages::where('path', row[0])->where('method', row[1])->first()->id;

This will return just the id.

And then in your foreach you can:

role_page::create([
           'page_id' => $page_id,
           'role_id' => $role_id
       ]);

You do have to explicitly state in your role_page model that it's not plural if your not refering to it in a relationship way:

protected $table = 'role_page';