gpt4 book ai didi

mysql - 如何检查数据透视表中匹配的两个值?

转载 作者:可可西里 更新时间:2023-11-01 08:24:19 25 4
gpt4 key购买 nike

这是我的代码:

$role_id = Auth::user()->role_id;
$page_id = Page::where('path', $request->path())->where('method', $_SERVER["REQUEST_METHOD"])->first()->id;

所以我同时拥有 role_idpage_id。我也有一张这样的 table :

// role_pages
+---------+---------+
| role_id | page_id |
+---------+---------+
| 1 | 1 |
| 1 | 2 |
| 1 | 4 |
| 1 | 8 |
| 2 | 1 |
| 2 | 3 |
| 2 | 7 |
| 3 | 1 |
| 3 | 9 |
+---------+---------+

注意到 role_pages(role_id, page_id) 上有一个复合唯一索引。如您所见,逻辑是:每个角色都有多个页面。

无论如何,我如何根据我的值检查上表中是否有任何行?请注意,我可以使用 EXISTS() 函数在纯 SQL 中执行此操作。但我想知道如何在 Laravel 中做到这一点?

最佳答案

How can I check is there any row in table

使用 contains()我描述的方法 here .

例子:

$page = Page::where('path', $request->path())->where('method', $_SERVER["REQUEST_METHOD"])->first();
$page->roles()->contains(Auth::user()->role_id);

或者:

$role = auth()->user()->role;
$pageId = Page::where('path', $request->path())->where('method', $_SERVER["REQUEST_METHOD"])->first()->id;
$role->pages()->contains($pageId);

关于mysql - 如何检查数据透视表中匹配的两个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47617610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com