简体   繁体   English

Laravel 8 eloquent 查询 - 将外部变量放入“连接后选择”

[英]Laravel 8 eloquent query - Put external variable to 'Select after join'

Below is the code where I am getting relevant records by joining 3 table and then the 'Select' statement at the end is fetching specific fields.下面是我通过加入 3 个表来获取相关记录的代码,然后最后的“选择”语句正在获取特定字段。 It's working perfectly.它运行良好。 Now I want to add the variable '$userName' in to 'Select' statement to pass it with each record to view.现在我想将变量 '$userName' 添加到 'Select' 语句中以将其与每条记录一起传递以查看。 also I want the key of $userName as userName and the value is dynamic.我也希望 $userName 的键为 userName 并且值是动态的。

here is the code.这是代码。

    $fromDate = request('fromDate');
    $toDate = request('toDate');
    $user = auth()->user();
    $userName = $user->name;
    
    $records = $user->cases()
        ->join('myrequests', 'mycases.id', 'myrequests.mycase_id')
        ->whereDate('myrequests.created_at', '>=', $fromDate)
        ->whereDate('myrequests.created_at', '<=', $toDate)
        ->select(
            'mycases.*',
            'myrequests.number',
            'myrequests.created_at',
            'myrequests.requested',
             **here I want the '$userName'**
        )->get();

I've tried 'username' => $userName and {{$userName}}我试过'username' => $userName{{$userName}}

but it's not working.但它不起作用。

you should get all the items from db then iterate over them:您应该从 db 获取所有项目,然后对其进行迭代:

 $records= ....

foreach ($records as $key => $item) {
   $item->username= $userName;
}

I'm assuming you want the string $userName returned as a 'username' column.我假设您希望将字符串$userName作为“用户名”列返回。 If so, add a selectRaw.如果是这样,请添加一个 selectRaw。

$records = $user->cases()
        ->join('myrequests', 'mycases.id', 'myrequests.mycase_id')
        ->whereDate('myrequests.created_at', '>=', $fromDate)
        ->whereDate('myrequests.created_at', '<=', $toDate)
        ->select(
            'mycases.*',
            'myrequests.number',
            'myrequests.created_at',
            'myrequests.requested',
        )
        ->selectRaw('"?" as username', [$userName])
        ->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM