2014-08-29 3 views
2

В моем приложении, у меня есть две модели в ассоциацииCakePHP найти ('все') возвращает только одну строку

УведомлениеbelongsToПрофиль

Это мой Notificaiton модальный

class Notification extends AppModel { 

    public $name = 'Notification'; 

public $belongsTo = array('Profile'); 

    public function getnotification($id = NULL){ 
    $result = $this->find('all',array(
     'conditions' => array(
     'Notification.receiver_id' => $id 
     ) 
    )); 
    return $result; 
    } 
} 

Array 
(
    [0] => Array 
     (
      [Notification] => Array 
       (
        [id] => 1 
        [profile_id] => 8 
        [receiver_id] => 1 
        [notification_text] => tester Sent you message on project Test 
        [notification_descriptions] => {"projectid":"2"} 
        [is_active] => 1 
        [created_on] => 2014-08-29 18:50:38 
        [modified_on] => 2014-08-29 18:50:38 
       ) 

      [Profile] => Array 
       (
        [id] => 8 
        [user_id] => 8 
        [u_id] => 63c0cd43 
        [profile_firstname] => tester 
        [profile_lastname] => seller 
        [profile_gender] => 1 
        [profile_dob] => 1999-08-13 
        [profile_paypalid] => [email protected] 
        [profile_company] => 
        [profile_occupation] => Web Developer 
        [profile_address] => 
        [profile_city] => 
        [profile_state] => 
        [country_id] => 106 
        [profile_postalcode] => 
        [currency_id] => 150 
        [timezone_id] => 93 
        [profile_avatar] => 
        [profile_role] => 2 
        [profile_status] => 1 
        [about_me] => "But I must explain to you how all this mistaken idea" 
        [profile_title] => 
        [rate_per_hour] => 
        [language_id] => 38 
        [visibility] => 
        [profile_rating] => 100 
        [is_active] => 1 
        [last_modified] => 2014-08-27 11:34:56 
        [rating] => 100 
       ) 

     ) 

) 

Но всегда возвращают первую строку из таблицы, даже если есть два или более ряда

Ожидаемый выходной

Array 
(
    [0] => Array 
     (
      [Notification] => Array 
       (
        [id] => 1 
        [profile_id] => 8 
        [receiver_id] => 1 
        [notification_text] => tester Sent you message on project Test 
        [notification_descriptions] => {"projectid":"2"} 
        [is_active] => 1 
        [created_on] => 2014-08-29 18:50:38 
        [modified_on] => 2014-08-29 18:50:38 
       ) 

      [Profile] => Array 
       (
        [id] => 8 
        [user_id] => 8 
        [u_id] => 63c0cd43 
        [profile_firstname] => tester 
        [profile_lastname] => seller 
        [profile_gender] => 1 
        [profile_dob] => 1999-08-13 
        [profile_paypalid] => [email protected] 
        [profile_company] => 
        [profile_occupation] => Web Developer 
        [profile_address] => 
        [profile_city] => 
        [profile_state] => 
        [country_id] => 106 
        [profile_postalcode] =>      
        [currency_id] => 150 
        [timezone_id] => 93 
        [profile_avatar] => 
        [profile_role] => 2 
        [profile_status] => 1 
        [about_me] => "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was" 
        [profile_title] => 
        [rate_per_hour] => 
        [language_id] => 38 
        [visibility] => 
        [profile_rating] => 100 
        [is_active] => 1 
        [last_modified] => 2014-08-27 11:34:56 
        [rating] => 100 
       ) 

     ) 

    [1] => Array 
     (
      [Notification] => Array 
       (
        [id] => 2 
        [profile_id] => 7 
        [receiver_id] => 1 
        [notification_text] => tester Sent you message on project Test 
        [notification_descriptions] => {"projectid":"2"} 
        [is_active] => 1 
        [created_on] => 2014-08-29 18:50:38 
        [modified_on] => 2014-08-29 18:50:38 
       ) 

      [Profile] => Array 
       (
        [id] => 7 
        [user_id] => 7 
        [u_id] => 63c0cd458 
        [profile_firstname] => teste 
        [profile_lastname] => person 
        [profile_gender] => 1 
        [profile_dob] => 1999-08-13 
        [profile_paypalid] => [email protected] 
        [profile_company] => 
        [profile_occupation] => Web Developer 
        [profile_address] => 
        [profile_city] => 
        [profile_state] => 
        [country_id] => 106 
        [profile_postalcode] => 
        [currency_id] => 150 
        [timezone_id] => 93 
        [profile_avatar] => 
        [profile_role] => 2 
        [profile_status] => 1 
        [about_me] => "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a c 
        [profile_title] => 
        [rate_per_hour] => 
        [language_id] => 38 
        [visibility] => 
        [profile_rating] => 100 
        [is_active] => 1 
        [last_modified] => 2014-08-27 11:34:56 
        [rating] => 100 
       ) 

     ) 

) 

В то время как $this->element('sql_dump'); показывает 3 строки были затронуты в связи с запросом, но когда я печать результат, он показывает только один результат, даже count & sizeof показать 1.

Рассмотрим profile_id как sender_id

Может ли один скажите мне, где и что я делаю неправильно?

+0

может быть проще понять вашу проблему, если вы разместите пример записей в таблице, массив, вы получаете и то, что ожидаемый выход – Nunser

+0

ожидается выход независимо находка («все») метод возвращает, все строки, которые удовлетворяют пройденным условиям – user3873381

ответ

1

Ваша функция getnotification - это просто поиск уведомлений одного пользователя. То, Что происходит здесь:

'conditions' => array(
    'Notification.receiver_id' => $id 
) 

Ваш ожидаемый результат показывает различные пользователи (user_id 7 и 8).

Что именно вы хотите получить?

  • Всех уведомления для одного пользователя (это то, что у вас есть)
  • Всех Уведомлений для всех пользователей
  • Всех пользователей с первым уведомлением

// EDIT 1: Получил это неправильно. Думаете, вам может понадобиться поведение Containable? Не проверял, вот идея:

В вашей модели: public $actsAs = array('Containable'); А в вашем Notification-модели:

public function getnotification($receiver_id = NULL){ 
    $this->find('all', array(
    'conditions' => array('Notification.receiver_id' => $receiver_id), 
    'fields' => array('Notification.profile_id', 'Notification.notification_text'), 
    'contain' => array(
     'Profile' => array(
     'fields' => array('Profile.id', 'Profile.profile_firstname', 'Profile.profile_lastname') 
    ) 
    ) 
)); 

// EDIT 2: Вы соединили все поля в ваших моделях? Я также не проверял, но я думаю, что это необходимо, чтобы связать все поля вместе ... В вашей модели профиля что-то вроде:

class Profile extends AppModel { 
    public $hasMany = array(
    'NotificationSender' => array(
     'className' => 'Notification', 
     'foreignKey' => 'profile_id' 
    ), 
    'NotificationReceiver' => array(
     'className' => 'Notification', 
     'foreignKey' => 'receiver_id' 
    ) 
); 
} 

И в вашем Notifications Модель:

class Notification extends AppModel { 
    public $belongsTo = array(
    'NotificationSender' => array(
     'className' => 'Profile', 
     'foreignKey' => 'profile_id' 
    ), 
    'NotificationReceiver' => array(
     'className' => 'Profile', 
     'foreignKey' => 'receiver_id' 
    ) 
); 
} 

Или similar ,Как я уже сказал, я не испытал это, извините. Но, возможно, это поможет вам найти решение ...

+0

Все уведомления одного пользователя с массивом профиля отправителя уведомления – user3873381

+0

Может быть, 'Containable' является решением? Я отредактировал свой ответ выше ... –

1

У меня была аналогичная проблема.

В первый раз моя находка («все») возвращает все, но через несколько дней просто возвращает один результат и не имеет никакого смысла.

Я нашел два способа исправить:

Первый путь был, когда я снял $ virtualFields из моей модели. Мои virtualFields были похожи на то, что:

public $virtualFields = array(
    'total' => 'SUM(Model.quantity*Model.value)' 
); 

Находка («все») просто не работает из-за этого. Может быть, проблема в том, что значение == null, но я не уверен.

Второй способ исправить это поместить поля возвращает в находке («все»), например:

$inputs = $this->InputsOutput->find('all', array(
     'fields' => array(
       'Model.id', 
      ), 
     'conditions' => $conditions, 
    )); 

Я надеюсь, что это может помочь.

0

У вас есть две подачи для оценки.

1. profile_rating 
2. rating 

Если я предполагаю, что одно из них является виртуальным полем, отмените его перед запросом на огонь.

unset($this->ModelName->virtualFields['fieldname']);