gpt4 book ai didi

php - 从 Laravel 中的 Mysql 数据透视表获取列并返回一个 JSON 对象

转载 作者:行者123 更新时间:2023-11-29 07:18:36 24 4
gpt4 key购买 nike

我正在开发一个使用 Laravel 构建的应用程序,在后端,我在 2 个表之间有一些 Eloquent 多对多关系,主要分别是角色和权限。还有一个名为 role_permission 的数据透视表。我在模型中创建了关系,在 Controller 中捕获了以下值以创建权限:name, description , slug, role_id

在逻辑上,我在权限表中存储名称、描述和 slug,而 role_id 存储在数据透视表 (role_permission) 中。这很好用。在响应中,我获取存储在权限表中的所有权限,并显示为 JSON 对象。

问题是我想获取数据透视表中的 role_id 并将其附加到显示为响应的每个 JSON 对象。

榜样

<?php

namespace Modules\API\Entities;
use Modules\API\Entities\Permission;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
protected $fillable = ['name' , 'slug' , 'description'];

/**
* A role has more than one permission
*/
public function permissions(){
return $this->belongsToMany(Permission::class , 'role_permission');
}
}

权限模型

<?php

namespace Modules\API\Entities;
use Modules\API\Entities\Role;
use Illuminate\Database\Eloquent\Model;

class Permission extends Model
{
protected $fillable = ['name' , 'slug' , 'description'];

/**
* A permission has more than one role
*/
public function roles(){
return $this->belongsToMany(Role::class , 'role_permission');
}
}

Controller 文件(PermissionController.php)

<?php

namespace Modules\API\Http\Controllers;

use Carbon\Carbon;
use Modules\API\Common\helpers\GeneralHelper;
use Illuminate\Http\Request;
use Illuminate\Database\QueryException;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Validator;
use Modules\API\Entities\Permission;

class PermissionController extends Controller
{
protected $requestTime;
protected $reference_number;

public function __construct()
{
$this->requestTime = Carbon::now()->toDateTimeString();
}

public function createPermission(Request $request) {

$validator = Validator::make($request->all(), [
'name' => 'required',
"slug" => 'required',
]);

if ($validator->fails()) {
$response = GeneralHelper::failureException("Validation Failed", $validator->errors()->all(), Carbon::now()->toDateTimeString());
}
else{

$name = $request->name;
$description = isset($request->description) ? $request->description : null;
$slug = isset($request->slug) ? $request->slug : null;
$role = isset($request->role_id) ? $request->role_id : null;

try{
$permission = new Permission;
$permission->name = $name;
$permission->slug = $slug;
$permission->description = $description;
$permission->save();

//Attach role to pivot table if permission is saved
if($permission->save() && !is_null($role)){
$permission->roles()->attach($role);
}

//Select specific columns from permissions table and return a JSON object
$permissions = Permission::select('id' , 'name', 'slug', 'description')->get()->toArray();

$response = response()->json(GeneralHelper::success("Permision Successfully added", "data", $permissions , Carbon::now()->toDateTimeString()));
} catch(QueryException $e){
$response = response()->json(GeneralHelper::failureException("Database Exception", $e->getMessage() . " at LINE " . $e->getLine(), Carbon::now()->toDateTimeString()), Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
return $response;
}
}

经过上述逻辑后 POSTMAN 中的示例响应

{
"request_time": "2019-09-03 07:54:54",
"response_time": "2019-09-03 07:54:54",
"status": "success",
"message": "Permision Successfully added",
"data": [
{
"id": 1,
"name": "Create Post",
"slug": "craete-post",
"description": "mnmnmn"
},
{
"id": 3,
"name": "delete User",
"slug": "del-user",
"description": "mnmnmn"
},
{
"id": 5,
"name": "Create User",
"slug": "create-user",
"description": "mnmnmn"
}
]
}

更新回复

{
"request_time": "2019-09-03 09:16:46",
"response_time": "2019-09-03 09:16:46",
"status": "success",
"message": "Permision Successfully added",
"data": [
{
"id": 1,
"name": "Kingston",
"slug": "kingston-red-iuy",
"description": "mnaskjas",
"roles": [
{
"id": 3,
"name": "Editor",
"slug": "editor",
"description": "Editor",
"created_at": "2019-09-02 06:37:08",
"updated_at": "2019-09-02 06:37:08",
"pivot": {
"permission_id": 9,
"role_id": 3
}
}
]
}
]
}`

在逻辑中使用此命令后:

 $permissions = Permission::select('id' , 'name', 'slug', 'description')->with('roles')->get()->toArray();

最佳答案

尝试改变:

$permissions = Permission::select('id' , 'name', 'slug', 'description')->get()->toArray();

进入:

$permissions = Permission::select('id' , 'name', 'slug', 'description')->with('roles')->get()->toArray();

$mappedPermissions = array_map(function ($permission) {
$permission['role_id'] = data_get($permission, '0.pivot.role_id');

unset($permission['roles']);

return $permission;
}, $permissions);

// Then use the $mappedPermissions from here on.

关于php - 从 Laravel 中的 Mysql 数据透视表获取列并返回一个 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57767747/

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