在我的laravel vue应用程序中,我有两个表,user表和user_document表.

在我的user_document表中,有一列名为added_by.

此列存储id个用户.

我的应用程序中有两个角色,管理员和普通用户.

我的用户可以通过vue组件将文档上载到系统.管理员也可以为其他用户上传文档.

用户可以在数据表中查看他们已经上传的文档详细信息.

在这个数据表中,我显示了一个名为Added By的列,其中显示了上传文档的用户(用户本人或管理员).

我有下面的控制器来获取和显示这些记录.

<?php

namespace App\Http\Controllers\Dashboard\Corporate\Employee;

use App\Company;
use App\Models\OtherDocument;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CompanyEmployeeOtherDocumentsController extends Controller
{
    /**
     * @param string $locale
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(string $locale, Company $company, User $user)
    {

        $otherDocuments = OtherDocument::where('user_id', $user->id)
            ->with('added_by_user')
            ->when(request('validity_status'), function ($query) {
                $query->where(function ($query) {
                    $query->when( in_array('active', request('validity_status')), function ($query) {
                        $query->where(function (Builder $query) {
                            $query->whereDate('issued_at', '<=', Carbon::now())
                                ->whereDate('expires_at', '>=', Carbon::now()->addMonth());
                        })->orWhere('is_valid_forever',1);
                    })->when( in_array('expires', request('validity_status')), function ($query) {
                        $query->orWhere(function (Builder $query) {
                            $query->whereDate('expires_at', '<=', Carbon::now()->addMonth())
                                ->whereDate('expires_at', '>=', Carbon::now());
                        });
                    })->when( in_array('expired', request('validity_status')), function ($query) {
                        $query->orWhereDate('expires_at', '<', Carbon::now());
                    });
                });
            })
            ->when(request('search_text'), function ($query) {
                $query->where('name', 'like', '%' . request('search_text') . '%');
            })
            ->paginate(request('per_page',config('statguru.pagination.limit')));

        for ($i=0; $i < count($otherDocuments); $i++) {
            $addedByUser = $otherDocuments[$i]->added_by_user;
            if ($addedByUser) {
                $otherDocuments[$i]['added_user_name'] = $addedByUser->first_name . ' ' . $addedByUser->last_name;
            }
        }

        return  response()->json($otherDocuments);

    }
}

在我的vue组件中,我有以下标题数组,

HeaderArray() {
            return [
                {text: 'Certificate', value: 'certificate'},
                {text: 'Added by', value: 'added_by_user_name'},
                {text: 'Institute', value: 'institute'},
                {text: 'Expiration', value: 'valid_date', classList: 'text-center'},
                {text: 'Validity', value: 'validity_status', classList: 'text-center'},
                {text: 'Verification', value: 'verification_status', classList: 'text-center'},
            ];
        },

This whole solution works perfectly.

但是现在不用这个for循环

for ($i=0; $i < count($otherDocuments); $i++) {
                $addedByUser = $otherDocuments[$i]->added_by_user;
                if ($addedByUser) {
                    $otherDocuments[$i]['added_user_name'] = $addedByUser->first_name . ' ' . $addedByUser->last_name;
                }
            }

我正试图通过Eloquent 来获得同样的结果

->with(['added_by_user' => function($q){
                $q->select('first_name', 'last_name');
             }]) 

当我用这个替换for循环时,它不会显示Added by user's first name....为了正确获取数据,我需要在Eloquent 的语言中进行哪些更改?

我用的是laravel 9

Update

我已经根据下面的Malkhazi Dartsmelidze答案更新了我的代码.

但我无法在数据表上显示名称.

以下是我更新的控制器,

<?php

namespace App\Http\Controllers\Dashboard\Corporate\Employee;

use App\Company;
use App\Models\OtherDocument;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CompanyEmployeeOtherDocumentsController extends Controller
{
    /**
     * @param string $locale
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(string $locale, Company $company, User $user)
    {

        $otherDocuments = OtherDocument::where('user_id', $user->id)
        ->with(['added_by_user' => function($q){
            $q->select('id', DB::raw('CONCAT(first_name, " ", last_name) as added_user_name'));
        }]) 
            ->when(request('validity_status'), function ($query) {
                $query->where(function ($query) {
                    $query->when( in_array('active', request('validity_status')), function ($query) {
                        $query->where(function (Builder $query) {
                            $query->whereDate('issued_at', '<=', Carbon::now())
                                ->whereDate('expires_at', '>=', Carbon::now()->addMonth());
                        })->orWhere('is_valid_forever',1);
                    })->when( in_array('expires', request('validity_status')), function ($query) {
                        $query->orWhere(function (Builder $query) {
                            $query->whereDate('expires_at', '<=', Carbon::now()->addMonth())
                                ->whereDate('expires_at', '>=', Carbon::now());
                        });
                    })->when( in_array('expired', request('validity_status')), function ($query) {
                        $query->orWhereDate('expires_at', '<', Carbon::now());
                    });
                });
            })
            ->when(request('search_text'), function ($query) {
                $query->where('name', 'like', '%' . request('search_text') . '%');
            })

            ->paginate(request('per_page',config('statguru.pagination.limit')));

        return  response()->json($otherDocuments);

    }
}

下面是vue头数组,

 HeaderArray() {
            return [
                {text: 'Certificate', value: 'certificate'},
                {text: 'Added by', value: 'added_user_name'},
                {text: 'Institute', value: 'institute'},
                {text: 'Expiration', value: 'valid_date', classList: 'text-center'},
                {text: 'Validity', value: 'validity_status', classList: 'text-center'},
                {text: 'Verification', value: 'verification_status', classList: 'text-center'},
            ];
        },

下面是我收到的数据

{
      "id": 6,
      "user_id": 941,
      "added_by": 869,
      "name": "driving licence",
      "issued_at": "2022-04-06T22:00:00.000000Z",
      "expires_at": "2022-04-29T22:00:00.000000Z",
      "is_valid_forever": 0,
      "document_url": null,
      "document_number": null,
      "file_name": "6-driving-licence.pdf",
      "url": "users/941/other-documents/6-driving-licence.pdf",
      "status": "EXPIRES",
      "created_at": "2022-04-07T03:39:47.000000Z",
      "updated_at": "2022-04-07T03:39:47.000000Z",
      "deleted_at": null,
      "expires_at_formatted": "30-04-2022",
      "validity_status": "EXPIRES",
      "remaining_days": 18,
      "added_by_user": {
        "id": 869,
        "added_user_name": "Satya Nadella",
        "country_code": null,
        "formatted_date_of_birth": "2022-04-11",
        "name": " ",
        "company_role": "admin",
        "profile_image": [
          {
            "url": "/img/statguru-user.png"
          }
        ],
        "inviter_user": "",
        "country": null,
        "media": [
          
        ]
      }
    },

推荐答案

你在这里做错了:

->with(['added_by_user' => function($q){
    $q->select('first_name', 'last_name');
}]) 

这种关系的工作方式是,laravel通过该查询的结果循环,并相互匹配users.iduser_documents.added_by,如果匹配,则附加它.

因为您只 Select 了first_namelast_name列,所以其中的id列始终是null列,并且与任何user_documents列都不匹配.

解决方案:

->with(['added_by_user' => function($q){
    $q->select('id', 'first_name', 'last_name');
}]) 

More convenient way to get full name:

use Illuminate\Support\Facades\DB;
...
->with(['added_by_user' => function($q){
    $q->select('id', DB::raw('CONCAT(first_name, " ", last_name) as added_user_name'));
}]) 

Edit:

由于前端要求added_user_name应该位于对象的第一级,所以您应该映射结果并将added_user_name移动到第一级,或者连接users表并从中获取结果:

Using join:

从查询中删除->with函数,并将其替换为join.

OtherDocument::where('user_id', $user->id)
    ->join('users', 'users.id', '=', 'user_document.added_by') // do not know exact names of columns
    ->select(DB::raw('user_document.*'), DB::raw('CONCAT(first_name, " ", last_name) as added_user_name'))
    ->...

Php相关问答推荐

当我们使用PHPUnit时,控制台中的--uses param到底起了什么作用以及如何使用?

过滤WooCommerce管理员订单列表(+HPOS)中包含其作者产品的订单

如何在不指定symfony列的情况下从数据库中获取行数组

无法在Laravel/Vue停靠容器中启动MySQL

如何修复条带元素中的错误&&客户端_机密&

在WooCommerce中禁用特定日期之前的免费送货

在冲突和几何上插入的Postgres参数化查询在PHP中不起作用

根据选定的字段值显示或隐藏WooCommerce注册字段

将SVG包含在另一个php生成的SVG中

WooCommerce中基于用户角色的不同产品差价

如何将WooCommerce产品从一个产品复制到另一个产品S

HTAccess重写一些URL,但将所有其他URL发送到另一个页面

未检测到laravel控制器

PHP 数组中第一级 node 到 XML 的唯一名称

使用自定义插件中的 WooCommerce 模板发送自定义邮箱

Google Drive API:为什么使用服务帐户在下载文件时会将我带到 Google Drive 登录窗口?

添加或删除优惠券后自动刷新 WooCommerce checkout 表单字段

如何故意创建不同的错误(404,500,419)? Lavravel PHP

正则表达式 (php) 匹配单个 [ 或单个 ] 但忽略 [[ ]] 之间的任何内容?

同时执行odbc_execute、odbc_fetch_row和odbc_result