1

私は 2 つのテーブル予約とメッセージを持っていますが、予約リクエストとメッセージを一度に受信トレイに表示したいと考えています。

$this->paginate = array(
            'conditions' => $conditions,'limit' =>10,
        'order'=>array('Booking.created'=>'DESC'));
    $bookings = $this->paginate('Booking');

    $this->paginate = array(
            'conditions' => $conditions,'limit' =>10,
        'order'=>array('MessageDetail.created'=>'DESC'));
    $messages = $this->paginate('MessageDetail');

両方のテーブルデータをマージしました( array_merge($bookings, $messages); )今、日付ごとに(または任意の条件で)ソートしたい

Array
(
[0] => Array
    (
        [Booking] => Array
            (
                [id] => 4
                [host_id] => 21
                [place_id] => 10
                [room_id] => 13
                [user_id] => 12
                [message_detail_id] => 16
                [created] => 2013-04-23 14:44:03
                [accept_date] => 
                [cancel_date] => 
            )

    )

[1] => Array
    (
        [Booking] => Array
            (
                [id] => 3
                [host_id] => 21
                [place_id] => 10
                [room_id] => 13
                [user_id] => 12
                [message_detail_id] => 13
                [created] => 2013-04-15 14:10:59
                [accept_date] => 2013-04-15 14:40:47
                [cancel_date] => 
            )

    )


[2] => Array
    (
        [MessageDetail] => Array
            (
                [id] => 17
                [message_id] => 2
                [user_id] => 12
                [sender_id] => 21
                [unread] => 0
                [created] => 2013-04-24 12:11:47
            )

    )

[3] => Array
    (
        [MessageDetail] => Array
            (
                [id] => 15
                [message_id] => 2
                [user_id] => 12
                [sender_id] => 21
                [booking_id] => 3
                [unread] => 0
                [created] => 2013-04-15 15:01:12
            )

    )

  )

前もって感謝します。

4

2 に答える 2

0

オプション #1: 「BookingAndMessage」という名前の 3 番目のモデルを作成します。モデルのafterSaveメソッドを (Booking と Message の両方で) 使用して、新しいモデルに重複レコードを作成できます。その後、適切な並べ替え順序で BookingAndMessage をクエリできます。

オプション #2 : 問題を解決するには、現状では、PHP のusort関数を使用することをお勧めします (ここでも説明されていますPHP Sort a multidimensional array by element using date )。

<?php

$BookingsAndMessages = array_merge($bookings, $messages);

function date_compare($a, $b)
{   
   $modelKeyA = array_key_exists('Booking',$a) ? 'Booking' : 'MessageDetail';
   $modelKeyB = array_key_exists('Booking',$b) ? 'Booking' : 'MessageDetail';
   $t1 = strtotime($a[$modelKeyA]['created']);
   $t2 = strtotime($b[$modelKeyB]['created']);
   return $t1 - $t2;
}

usort($BookingsAndMessages, 'date_compare');
// Would sort the merged records by `created` date
?>

オプション 2 の欠点は、フィールド (および並べ替え方向) ごとにルールを作成する必要があることです。

于 2015-02-24T19:25:25.627 に答える