CakePHP - Отношения Вопрос - Posts.Child принадлежит пользователю, как определить? - PullRequest
0 голосов
/ 08 августа 2011

Ниже приведена модель сообщений, и, как вы можете видеть, у меня есть отношение к каждому сообщению, так что сведения о пользователе также извлекаются вместе с сообщением.Мне также хотелось бы точно такое же поведение для Posts.Children (см. Определение hasMany ниже).

ВОПРОС:

Как мне также применить отношение ownTo к Posts.Children (Posts.Child assignTo User) ??

<?php
class Post extends AppModel {

    var $name = 'Post';

    var $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'post_owner',
          'fields' => array( "User.id" , "User.first_name" , "User.last_name" )
        )
    );

    // -=> 
    var $hasMany = array(
        'Child' => array(
            'className' => 'Post',
            'foreignKey' => 'parent_id',
        'conditions' => array( "Child.active" => "1" ),
        'limit' => '2',
        'order' => 'time DESC'
        )
    );
}
?>

А вот код PostsController, который я сейчас использую:

class PostsController extends AppController {    
    var $helpers = array ('Html','Form');
    var $name = 'Posts';

    function index() {
        $conditions = array( "Post.parent_id" => "0" , "Post.active" => "1" );
        $this->set(     'posts', $this->Post->find('all',array(   'conditions'=>$conditions     ))   );
        debug(   $this->Post->find('all',array(   'conditions'=>$conditions  ))   );
}

"что выводится, если вы вызываете debug ($ this->Post-> Child); в постах контроллер?Вот оно:

Post Object
(
    [name] => Post
    [hasMany] => Array
        (
            [Child] => Array
            (
                [className] => Post
                [foreignKey] => parent_id
                [conditions] => Array
                    (
                        [Child.active] => 1
                    )

                [fields] => 
                [order] => 
                [limit] => 
                [offset] => 
                [dependent] => 
                [exclusive] => 
                [finderQuery] => 
                [counterQuery] => 
            )

    )

[belongsTo] => Array
    (
        [User] => Array
            (
                [className] => User
                [foreignKey] => dom
                [fields] => Array
                    (
                        [0] => User.id
                        [1] => User.first_name
                        [2] => User.last_name
                    )

                [conditions] => 
                [order] => 
                [counterCache] => 
            )

    )

[useDbConfig] => default
[useTable] => posts
[displayField] => title
[id] => 
[data] => Array
    (
    )

[table] => posts
[primaryKey] => id
[_schema] => Array
    (
        [active] => Array
            (
                [type] => integer
                [null] => 
                [default] => 1
                [length] => 1
            )

        [id] => Array
            (
                [type] => integer
                [null] => 
                [default] => 
                [length] => 11
                [key] => primary
            )

        [parent_id] => Array
            (
                [type] => integer
                [null] => 
                [default] => 0
                [length] => 11
            )

        [time] => Array
            (
                [type] => integer
                [null] => 
                [default] => 0
                [length] => 11
            )

        [dom] => Array
            (
                [type] => integer
                [null] => 
                [default] => 
                [length] => 11
            )

        [sub] => Array
            (
                [type] => integer
                [null] => 
                [default] => 
                [length] => 11
            )

        [created] => Array
            (
                [type] => datetime
                [null] => 
                [default] => 
                [length] => 
            )

        [modified] => Array
            (
                [type] => datetime
                [null] => 
                [default] => 
                [length] => 
            )


        [text] => Array
            (
                [type] => string
                [null] => 
                [default] => 
                [length] => 4096
                [collate] => latin1_swedish_ci
                [charset] => latin1
            )

    )

[validate] => Array
    (
    )

[validationErrors] => Array
    (
    )

[tablePrefix] => 
[alias] => Child
[tableToModel] => Array
    (
        [posts] => Child
        [users] => User
    )

[logTransactions] => 
[cacheQueries] => 
[hasOne] => Array
    (
    )

[hasAndBelongsToMany] => Array
    (
    )

[actsAs] => 
[Behaviors] => BehaviorCollection Object
    (
        [modelName] => Child
        [_attached] => Array
            (
            )

        [_disabled] => Array
            (
            )

        [__methods] => Array
            (
            )

        [__mappedMethods] => Array
            (
            )

    )

[whitelist] => Array
    (
    )

[cacheSources] => 1
[findQueryType] => 
[recursive] => 1
[order] => 
[virtualFields] => Array
    (
    )

[__associationKeys] => Array
    (
        [belongsTo] => Array
            (
                [0] => className
                [1] => foreignKey
                [2] => conditions
                [3] => fields
                [4] => order
                [5] => counterCache
            )

        [hasOne] => Array
            (
                [0] => className
                [1] => foreignKey
                [2] => conditions
                [3] => fields
                [4] => order
                [5] => dependent
            )

        [hasMany] => Array
            (
                [0] => className
                [1] => foreignKey
                [2] => conditions
                [3] => fields
                [4] => order
                [5] => limit
                [6] => offset
                [7] => dependent
                [8] => exclusive
                [9] => finderQuery
                [10] => counterQuery
            )

        [hasAndBelongsToMany] => Array
            (
                [0] => className
                [1] => joinTable
                [2] => with
                [3] => foreignKey
                [4] => associationForeignKey
                [5] => conditions
                [6] => fields
                [7] => order
                [8] => limit
                [9] => offset
                [10] => unique
                [11] => finderQuery
                [12] => deleteQuery
                [13] => insertQuery
            )

    )

[__associations] => Array
    (
        [0] => belongsTo
        [1] => hasOne
        [2] => hasMany
        [3] => hasAndBelongsToMany
    )

[__backAssociation] => Array
    (
    )

[__insertID] => 
[__numRows] => 
[__affectedRows] => 
[_findMethods] => Array
    (
        [all] => 1
        [first] => 1
        [count] => 1
        [neighbors] => 1
        [list] => 1
        [threaded] => 1
    )

[User] => User Object
    (
        [name] => User
        [validate] => Array
            (
                [name] => Array
                    (
                        [rule] => Array
                            (
                                [0] => minLength
                                [1] => 4
                            )

                        [message] => Name has to be at least four characters
                    )

                [email] => Array
                    (
                        [rule] => Array
                            (
                                [0] => email
                            )

                        [message] => Please enter a valid email
                    )

                [username] => Array
                    (
                        [Username has to be at least four characters] => Array
                            (
                                [rule] => Array
                                    (
                                        [0] => minLength
                                        [1] => 4
                                    )

                            )

                        [This username is already taken, please try another] => Array
                            (
                                [rule] => isUnique
                            )

                    )

                [password] => Array
                    (
                        [Password cannot be empty] => Array
                            (
                                [rule] => Array
                                    (
                                        [0] => notEmpty
                                    )

                            )

                        [Password must be at least four characters] => Array
                            (
                                [rule] => Array
                                    (
                                        [0] => minLength
                                        [1] => 4
                                    )

                            )

                        [Passwords must match] => Array
                            (
                                [rule] => Array
                                    (
                                        [0] => passwordCompare
                                        [1] => password_confirm
                                    )

                            )

                    )

            )

        [useDbConfig] => default
        [useTable] => users
        [displayField] => id
        [id] => 
        [data] => Array
            (
            )

        [table] => users
        [primaryKey] => id
        [_schema] => Array
            (
                [id] => Array
                    (
                        [type] => integer
                        [null] => 
                        [default] => 
                        [length] => 11
                        [key] => primary
                    )

                [type] => Array
                    (
                        [type] => boolean
                        [null] => 
                        [default] => 1
                        [length] => 1
                    )

                [is_active] => Array
                    (
                        [type] => boolean
                        [null] => 
                        [default] => 1
                        [length] => 1
                    )



                [gender] => Array
                    (
                        [type] => boolean
                        [null] => 
                        [default] => 1
                        [length] => 1
                    )

                [first_name] => Array
                    (
                        [type] => string
                        [null] => 
                        [default] => 
                        [length] => 200
                        [collate] => latin1_swedish_ci
                        [charset] => latin1
                    )

                [last_name] => Array
                    (
                        [type] => string
                        [null] => 
                        [default] => 
                        [length] => 200
                        [collate] => latin1_swedish_ci
                        [charset] => latin1
                    )

                [email] => Array
                    (
                        [type] => string
                        [null] => 
                        [default] => 
                        [length] => 200
                        [collate] => latin1_swedish_ci
                        [charset] => latin1
                    )

                [username] => Array
                    (
                        [type] => string
                        [null] => 
                        [default] => 
                        [length] => 200
                        [collate] => latin1_swedish_ci
                        [charset] => latin1
                    )

                [password] => Array
                    (
                        [type] => string
                        [null] => 
                        [default] => 
                        [length] => 200
                        [collate] => latin1_swedish_ci
                        [charset] => latin1
                    )

                [created] => Array
                    (
                        [type] => datetime
                        [null] => 
                        [default] => 
                        [length] => 
                    )

                [modified] => Array
                    (
                        [type] => datetime
                        [null] => 
                        [default] => 
                        [length] => 
                    )

                [bio] => Array
                    (
                        [type] => string
                        [null] => 
                        [default] => 
                        [length] => 2048
                        [collate] => latin1_swedish_ci
                        [charset] => latin1
                    )

            )

        [validationErrors] => Array
            (
            )

        [tablePrefix] => 
        [alias] => User
        [tableToModel] => Array
            (
                [users] => User
            )

        [logTransactions] => 
        [cacheQueries] => 
        [belongsTo] => Array
            (
            )

        [hasOne] => Array
            (
            )

        [hasMany] => Array
            (
            )

        [hasAndBelongsToMany] => Array
            (
            )

        [actsAs] => 
        [Behaviors] => BehaviorCollection Object
            (
                [modelName] => User
                [_attached] => Array
                    (
                    )

                [_disabled] => Array
                    (
                    )

                [__methods] => Array
                    (
                    )

                [__mappedMethods] => Array
                    (
                    )

            )

        [whitelist] => Array
            (
            )

        [cacheSources] => 1
        [findQueryType] => 
        [recursive] => 1
        [order] => 
        [virtualFields] => Array
            (
            )

        [__associationKeys] => Array
            (
                [belongsTo] => Array
                    (
                        [0] => className
                        [1] => foreignKey
                        [2] => conditions
                        [3] => fields
                        [4] => order
                        [5] => counterCache
                    )

                [hasOne] => Array
                    (
                        [0] => className
                        [1] => foreignKey
                        [2] => conditions
                        [3] => fields
                        [4] => order
                        [5] => dependent
                    )

                [hasMany] => Array
                    (
                        [0] => className
                        [1] => foreignKey
                        [2] => conditions
                        [3] => fields
                        [4] => order
                        [5] => limit
                        [6] => offset
                        [7] => dependent
                        [8] => exclusive
                        [9] => finderQuery
                        [10] => counterQuery
                    )

                [hasAndBelongsToMany] => Array
                    (
                        [0] => className
                        [1] => joinTable
                        [2] => with
                        [3] => foreignKey
                        [4] => associationForeignKey
                        [5] => conditions
                        [6] => fields
                        [7] => order
                        [8] => limit
                        [9] => offset
                        [10] => unique
                        [11] => finderQuery
                        [12] => deleteQuery
                        [13] => insertQuery
                    )

            )

        [__associations] => Array
            (
                [0] => belongsTo
                [1] => hasOne
                [2] => hasMany
                [3] => hasAndBelongsToMany
            )

        [__backAssociation] => Array
            (
            )

        [__insertID] => 
        [__numRows] => 
        [__affectedRows] => 
        [_findMethods] => Array
            (
                [all] => 1
                [first] => 1
                [count] => 1
                [neighbors] => 1
                [list] => 1
                [threaded] => 1
            )

        )

    [Child] => Post Object
 *RECURSION*
)

Ответы [ 2 ]

2 голосов
/ 08 августа 2011

Вы положили его в модель Children.

var $belongsTo = array( 'Post' );

Кстати, вы отправили модель, а не контроллер. Надеюсь, это всего лишь опечатка, и вы нашли это в правильном месте.

Также неясно, назовите ли вы модель «Ребенок» или «Дети». Отношение $hasMany использует Children, но в вопросе, который вы говорите Posts.Child - правильно ли настроен перегиб?

РЕДАКТИРОВАТЬ: Я, возможно, неправильно понял вопрос: если вы хотите иметь отношения hasMany, у вас уже есть это. Проблема заключается либо в способе получения данных, либо в определении взаимосвязи.

1 голос
/ 08 августа 2011

вам не нужно ничего делать, ребенок также является сообщением, поэтому также принадлежит пользователю.(И вы должны назвать его «Дитя», а не «Дети»)

С содержанием можно попробовать: $this->Post->find('all',array('contain'=>array('Child'=>array('User'))));

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...