【问题标题】:Get the username on a self relationship - Cakephp 3获取自我关系的用户名 - Cakephp 3
【发布时间】:2017-05-30 14:44:41
【问题描述】:

我正在构建一个“关注系统”(如 twitter),我正在尝试获取关注用户名。但我只能得到 follower_id 或 follow_id。这就是我得到的:

//UsersFollowersTable.php

public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('users_followers');

    $this->addBehavior('Timestamp');

    $this->belongsTo('Followeds', [ //who i'm following
        'className' => 'Users',
        'unique' => true,
        'foreignKey' => 'follower_id',
        'targetForeignKey' => 'Users.id',
        'joinType' => 'INNER'
    ]);
    $this->belongsTo('Followers', [ //my followers
        'className' => 'Users',
        'unique' => true,
        'foreignKey' => 'followed_id',
        'targetForeignKey' => 'Users.id',
        'joinType' => 'INNER'
    ]);
}

//UsersTable.php

公共函数初始化(数组$config) { 父::初始化($config);

    $this->hasMany('Followed', [
        'className' => 'UsersFollowers',
        //'joinTable' => 'users_followers',
        'unique' => true,
        'foreignKey' => 'follower_id',
        'targetForeignKey' => 'id'
    ]);

      $this->hasMany('Follower', [
        'className' => 'UsersFollowers',
        //'joinTable' => 'users_followers',
        'unique' => true,
        'foreignKey' => 'followed_id',
        'targetForeignKey' => 'id'
    ]);


}

我怎样才能得到 $user->followed “用户名”? //用户控制器 公共功能视图($id = null) {

$user = $this->Users->get($id, [
        'contain' => ['Collections', 'Images', 'Items', 'Likes', 'Messages', 'Profiles', 'Ratings', 'Followed', 'Follower' ]
    ]);

}

谢谢

【问题讨论】:

  • 你用debug($user->excute());查看结果了吗?

标签: cakephp


【解决方案1】:

用户有很多关注,所以$user->followedCollection,循环它:

if ($user->has('followed')) {
    foreach ($user->followed as $followed) {
        debug($followed->username);
    }
}

【讨论】:

  • 我无法获取用户名。看:
猜你喜欢
  • 1970-01-01
  • 2023-03-03
  • 2023-03-04
  • 2023-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多