对 Laravel 执行特定的 SQL 查询
Perform specific SQL query on Laravel
我有一个管理商店、用户和角色的应用程序。
每个用户可以是所有者、主管、雇员或管理员。
了解用户是否具有 admin、supervisor 或 employee 权限的方法是通过 role_user table 连接用户、商店和角色(admin 角色集 NULL shop_id 字段中的值 role_shop table)。相反,所有者是通过 shops table.
上的 user_id 字段获得的
我想在我的用户模型上执行一个函数来获取用户拥有的所有角色。
以下查询有效,但我不知道如何在 Eloquent 的查询生成器上执行它
SELECT priority, role, shop
FROM (
(
SELECT 1.5 AS priority, "owner" AS role, shops.id AS shop
FROM shops
WHERE shops.user_id = 1
)
UNION
(
SELECT roles.id AS priority, roles.name AS role, role_shop.shop_id AS shop
FROM role_shop
JOIN roles ON (roles.id = role_shop.role_id)
WHERE role_shop.user_id = 1
)
) AS result
ORDER BY priority
感谢大家的帮助!
使用join
方法并将结果分组user_id
$roles = DB::table('roles')
->where('user_id', '=', 1)
->join('shops', 'shops.user_id', '=', 'roles.user_id')
//Add other tabalse as join then
->select('roles.*')
->groupby('roles.user_id')
->get();
Ps: Sorry my code is not complete, I'm with mobile, you can find
samples in laravel docs
因为你这里有两个select,我建议先做两个query,然后join两个query得到并集的结果。
$query1 = Shop::select(
DB::RAW('"1.5" AS "priority"'),
DB::RAW('"owner" AS "role"'),
DB::RAW('id AS "shop"')
)
->where('user_id', 1)
->orderBy('priority');
$query2 = RoleShop::join('roles AS roles', 'role_shop.role_id', '=', 'roles.id')
->select(
DB::RAW('roles.id AS "priority"'),
DB::RAW('roles.name AS "role"'),
DB::RAW('role_shop.shop_id AS "shop"'),
)
->where('role_shop.user_id', 1)
->orderBy('priority');
$result = $query1->union($query2)->get();
它可能不是 100% 正确,但请随意调整它以获得您想要的。
我有一个管理商店、用户和角色的应用程序。
每个用户可以是所有者、主管、雇员或管理员。
了解用户是否具有 admin、supervisor 或 employee 权限的方法是通过 role_user table 连接用户、商店和角色(admin 角色集 NULL shop_id 字段中的值 role_shop table)。相反,所有者是通过 shops table.
上的 user_id 字段获得的我想在我的用户模型上执行一个函数来获取用户拥有的所有角色。
以下查询有效,但我不知道如何在 Eloquent 的查询生成器上执行它
SELECT priority, role, shop
FROM (
(
SELECT 1.5 AS priority, "owner" AS role, shops.id AS shop
FROM shops
WHERE shops.user_id = 1
)
UNION
(
SELECT roles.id AS priority, roles.name AS role, role_shop.shop_id AS shop
FROM role_shop
JOIN roles ON (roles.id = role_shop.role_id)
WHERE role_shop.user_id = 1
)
) AS result
ORDER BY priority
感谢大家的帮助!
使用join
方法并将结果分组user_id
$roles = DB::table('roles')
->where('user_id', '=', 1)
->join('shops', 'shops.user_id', '=', 'roles.user_id')
//Add other tabalse as join then
->select('roles.*')
->groupby('roles.user_id')
->get();
Ps: Sorry my code is not complete, I'm with mobile, you can find samples in laravel docs
因为你这里有两个select,我建议先做两个query,然后join两个query得到并集的结果。
$query1 = Shop::select(
DB::RAW('"1.5" AS "priority"'),
DB::RAW('"owner" AS "role"'),
DB::RAW('id AS "shop"')
)
->where('user_id', 1)
->orderBy('priority');
$query2 = RoleShop::join('roles AS roles', 'role_shop.role_id', '=', 'roles.id')
->select(
DB::RAW('roles.id AS "priority"'),
DB::RAW('roles.name AS "role"'),
DB::RAW('role_shop.shop_id AS "shop"'),
)
->where('role_shop.user_id', 1)
->orderBy('priority');
$result = $query1->union($query2)->get();
它可能不是 100% 正确,但请随意调整它以获得您想要的。