如何按旧日期获取多个表的行(逐行)

时间:2018-06-14 22:49:40

标签: php mysql laravel

我使用 Laravel ,例如我有3 Models,我得到当前用户记录的数据如下:

    $questions = Auth::user()->questions()->orderBy('created_at','desc')->get()->toArray();
    $answers = Auth::user()->answers()->orderBy('created_at','desc')->get()->toArray();
    $comments = Auth::user()->answerComments()->orderBy('created_at','desc')->get()->toArray();

例如,数组$question& $answers& $comments有时间戳列(created_atupdated_at),但没有相同的列,如何创建新数组以按最早的日期存储三个数组?

我这样做是为了获得个人历史。 (评论,答案,问题)。

抱歉我的英语。

2 个答案:

答案 0 :(得分:1)

您可以使用UNION组合所有表,然后按外部查询中的创建者字段对结果进行排序 像这样:

SELECT * FROM (
(
  Select question as data , 'question' as type, created_at
  FROM questions_table 
  where ( questions_table.user = [your_user_id])
)
UNION
(
  SELECT answer as data, 'answer' as type, created_at
  FROM answers_table
  where ( answers_table.user = [your_user_id])
)
UNION
(
   SELECT comment as data, 'comment' as type, created_at
   FROM comments_table
   where ( comments_table.user = [your_user_id])
)
) 
ORDER BY created_at DESC

这将合并所有数据,然后按创建日期排序

答案 1 :(得分:1)

我完全不明白你的问题,你只能使用以下行为来做到这一点:

1-first :设置function以从日期数组返回最小日期:

function minDate($dates){
    $now = date("Y-m-d h:i:s", time()); // the time now
    $oldest = $now;   // the oldest date 
    $row = null;      // oldest row will be returned
    foreach($dates as $date){ 
        $curDate = $date['created_at'];
        if ($curDate < $oldest) {
            $oldest = $curDate;
            $row = $date ; // the old row
        }
    }
    return $row;
}

1秒:获取这三个数组后的tand:

$questions = Auth::user()->questions()->orderBy('created_at','desc')->get()->toArray();
$answers = Auth::user()->answers()->orderBy('created_at','desc')->get()->toArray();
$comments = Auth::user()->answerComments()->orderBy('created_at','desc')->get()->toArray();

$data = [$questions ,$answers ,$comments];
$mixed = []; // this for store all rows (finish result)
$k = 0; // We will work on the first row
while(!empty($data[0]) || !empty($data[1]) || !empty($data[2])){

          $arr = [];
          foreach ($data as $d)
          if(isset($d[$k]['created_at']))
               $arr[] = $d[$k]; // Store the first rows in $arr
          $row = minDate($arr); // $row is the oldest row in all arrays
          $mixed[] = $row;  // $the oldest will be stored in $mixed

          for($i=0;$i<=2;$i++){ // Here is the search for the oldest row
              if(isset($data[$i][$k]) && $data[$i][$k] === $row){
                   array_shift($data[$i]); // remove the oldest row 
              }
          }

}
dd($mixed); // and you got $mixed content all rows of all arrays order by created_at