这是我的表结构:
// 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 |
+---------+---------+
现在我想根据这个数组在role_page
表中插入多行:(注意我有$role_id
)
$arr = [['list_role', 'get'], ['list_voucher/activate', 'get']]
$role_id = 4; // for example
所以预期的输出是:
// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+
| 4 | 1 |
| 4 | 4 |
+---------+---------+
如何通过加入来做到这一点?
目前我通过这样的$arr
循环来做到这一点:
$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;
}
答案 0 :(得分:1)
试试这个
页面模型(您可能必须自定义此关系)
public function roles(){
return $this->belongsToMany(Role::class, 'role_page', 'page_id', 'role_id')
}
然后
$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);
}
答案 1 :(得分:0)
$page_id = pages::where('path', row[0])->where('method', row[1])->first();
这会返回一个对象。
$page_id = pages::where('path', row[0])->where('method', row[1])->first()->id;
这将只返回id。
然后在你的foreach中你可以:
role_page::create([
'page_id' => $page_id,
'role_id' => $role_id
]);
如果你没有以关系的方式引用它,你必须在你的role_page模型中明确声明它不是复数:
protected $table = 'role_page';