Laravel 5+,在一个数组中收集多个相同的集合

时间:2018-04-08 19:32:29

标签: php laravel collections eloquent laravel-5.6

所以我有一个问题。我正在尝试收集用户' Log'信息(登录此上下文表示维护问题或相关内容)。现在返回的每个日志集合都基于它们的用户类型。用户也可以是多于一种类型,例如租户,但也可以是系统下的第三方。所以我需要返回所有日志,即使它们有多种用户类型。 这是我的代码:

    public function returnLogs() {

    if($this->isPosidaciousAdmin()) {

        //All logs
        return Log::all()->latest();

    } else {        

        //coalesce logs for each user type the user is

        if($this->isStaff()) {

            //Logs created under working agency ID and log assignee logs
            $logs[] = Log::where('agency_id', $this->activeAgencyId())
                        ->orWhere('created_by', $this->user_id)
                        ->latest()
                        ->get();

        } 

        if($this->isThirdParty()) {

            //Log Assignees logs

            //Get all assigned log IDs
            $assignedLogs = LogAssignee::select('log_id')->where('user_id', $this->user_id);

            //Find all logs with assigned log IDs
            $logs[] = Log::whereIn('log_id', $assignedLogs)->latest()->get();

        } 

        if($this->isTenant()) {

            //Logs at current property and logs created by tenant
            //If tenant currently has a tenancy
            if($this->currentProperty() !== null) {
                $logs[] = Log::where('created_by', $this->user_id)
                            ->orWhere('property_id', $this->currentProperty()->property_id)  
                            ->latest()               
                            ->get();
            } else {
                $logs[] = null;
            }
        }
    }

    return $logs;
}

这个问题是,如果输出是多个用户类型,则输出是每个条目拆分数组:

=> [
 Illuminate\Database\Eloquent\Collection {#829
   all: [
     App\Log {#830
       log_id: 1,
       log_title: "Test Log",
       log_type: "Maintenance",
       log_severity: "Normal",
       log_status: "Open",
       agency_id: 1,
       property_id: 1,
       created_by: 4,
       created_at: "2018-04-08 19:05:54",
       updated_at: "2018-04-08 20:07:48",
       deleted_at: null,
     },
   ],
 },
 Illuminate\Database\Eloquent\Collection {#837
   all: [],
 },

显然,数组的第二部分没有数据,但是你得到了返回的格式。这在循环数组时引起问题。我只是想知道我是否可以将所有日志信息都返回到数组中的相同索引[0]? (然后我可以返回$ log [0])。

由于

1 个答案:

答案 0 :(得分:3)

您可以在集合中使用merge()方法。

在您当前返回日志的位置尝试以下代码;

$mergedLogs = $logs[0];

// although arrays begin at 0 we've already got the first one
for ($i = 1; $i < count($logs); $i++) {
    $mergedLogs = $mergedLogs->merge($logs[$i]);
}

return $mergedLogs;