使用用户ID数组添加/更新db列的SQL代码

时间:2017-07-20 17:11:42

标签: mysql ajax wordpress

我在WP中创建了一个自定义数据库,我希望创建用户关注者列表并跟随(基于ID)

$table_name = $wpdb->prefix . 'addon_users';

        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            user_id bigint(20) NOT NULL,
            username bigint(20) NOT NULL,
            following bigint(20) NOT NULL,
            followers bigint(20) NOT NULL,          
            PRIMARY KEY  (id),
            UNIQUE KEY id (id)
        ) $charset_collate;";

我的AJAX电话:

public function addon_ajax_follow_me() {

            check_ajax_referer( 'km-ajax-create-nonce', 'security' );   

            $current_user   = get_current_user_id();
            $target_user    = isset( $_POST['data-follow-user'] ) ? $_POST['data-follow-user'] : false;

            if( ! empty( $_POST['data-follow-user'] ) ) {           
                $this->cgc_follow_user( $current_user, $target_user );
            }       

            wp_die();   

    }

关注用户功能:

public function cgc_follow_user( $current_user = 0, $user_to_follow = 0  ) {

            ...

            $args = array(
                'user_id'   => $current_user,
                'following' => $user_to_follow
            );

            $this->add_follower( $args );
        }

此功能用于更新数据库以及我需要帮助的地方。

public function add_follower( $args = array() ) {

            global $wpdb;

            $defaults = array(
                'user_id'       => '',
                'following'     => ''
            );

            $args = wp_parse_args( $args, $defaults );

            $add = $wpdb->query(
                $wpdb->prepare(
                    "INSERT INTO {$this->table} SET
                        `user_id`       = '%d',
                        `following`     = '%d'
                    ;",
                    absint( $args['user_id'] ),
                    absint( $args['following'] )
                )
            );

            if ( $add )
                return $wpdb->insert_id;

            return false;
        }

每次用户跟随另一个用户时,这将在数据库中创建一个新条目。但我希望建立一个用户ID数组。像这样:

umeta_id   user_id   username    following      followers
    1         1       Yoonah     5,12,58,66      45, ...       
    2         5     Elisabeth     2,8,66         1,45, ...
    3         8        Max        45,9,99         5, ...
    4        45        Ace        1,5,87          8, ...

我偶然发现的是使用适当的SQL代码添加ID数组。

另外,当'Yoonah'(1)跟随Elisabeth(5)时,Elisabeth(5)的followers专栏也应该用'Yoonah'(1)更新。

非常感谢任何帮助。

修改

enter image description here

2 个答案:

答案 0 :(得分:1)

我不太清楚你的问题,我希望这就是你所说的。

更新: 我测试了这个代码它正在工作,唯一的问题是如果user_id不存在而我创建了一个强制性的“用户名”,但我认为因为你使用的是当前用户登录的WordPress,它应该可以使用没问题就像它对我有用。

 Class TestThis {
    var $table = 'users';

    function __construct() {
        add_action( "wp_ajax_add_follower", array( $this, "add_follower" ) );
    }

    function add_follower() {
        $current_user = wp_get_current_user();
        $args = array(
            'user_id'   => $current_user->ID,
            'follow_to' => $_POST['user_to_follow']
        );

        $response = $this->add_following( $args );
        if ( ! empty( $response ) && $response !== FALSE ) {
            $args = array(
                'user_id'   => $_POST['user_to_follow'],
                'followed_by' => $current_user->ID
            );

            $this->add_followed_by( $args );
        }

        wp_die();
    }

    function add_following ( $args = array() ) {
        global $wpdb;

        $defaults = array(
            'user_id'       => "",
            'follow_to'     => "",
            'username'      => "Default Username"
        );

        $args = wp_parse_args( $args, $defaults );

        // First you have to check if the user already exists and return his Following Row
        $following = array();
        $existing = $wpdb->get_var( $wpdb->prepare( "SELECT following FROM {$this->table} WHERE user_id = %d", $args["user_id"] ) );

        if( ! empty( $existing ) ) {
            $following = json_decode( $existing );
        }

        // We check if this user ($args["user_id"]) is already following the $args["follow_to"] user.
        if( in_array( $args["follow_to"], $following ) )
        {
            return TRUE;
        }else{
            array_push( $following, $args['follow_to'] );
        }
        // We verify if the user exists and update the value, if he does not and we sent username, then, we create it.
        if( null === $existing && ! empty( $args['username'] ) ) {
            $wpdb->insert(
                $this->table,
                array(
                    'user_id' => $args['user_id'],
                    'username' => $args['username'],
                    'following' => json_encode( $following ),
                    'followers' => json_encode( array() )
                ),
                array(
                    '%d',
                    '%s',
                    '%s',
                    '%s'
                )
            );

            return $wpdb->insert_id;
        } else {
            $updated = $wpdb->update(
                $this->table,
                array(
                    'following' => json_encode( $following )
                ),
                array( 
                    'user_id' => $args["user_id"]
                ),
                "%s",
                "%d"
            );

            return $updated;
        }
    }

    function add_followed_by( $args, $defaults ) {
        global $wpdb;

        $defaults = array(
            'user_id'       => "",
            'followed_by'   => "",
            'username'      => "Default Username"
        );

        $args = wp_parse_args( $args, $defaults );

        // First you have to check if the user already exists and return his Followers Row
        $followers = array();
        $existing = $wpdb->get_var( $wpdb->prepare( "SELECT followers FROM {$this->table} WHERE user_id = %d", $args["user_id"] ) );

        if( ! empty( $existing ) ) {
            $followers = json_decode( $existing );
        }

        // We check if this user ($args["user_id"]) is already followed by $args["followed_by"] user.
        if( in_array( $args["followed_by"], $followers ) )
        {
            return TRUE;
        }else{
            array_push( $followers, $args['followed_by'] );
        }

        // We verify if the user exists and update the value, if he does not and we sent username, then, we create it.
        if( null === $existing && ! empty( $args['username'] ) ) {
            $wpdb->insert(
                $this->table,
                array(
                    'user_id' => $args['user_id'],
                    'username' => $args['username'],
                    'following' => json_encode( array() ),
                    'followers' => json_encode( $followers )
                ),
                array(
                    '%d',
                    '%s',
                    '%s',
                    '%s'
                )
            );

            return $wpdb->insert_id;
        } else {
            $updated = $wpdb->update(
                $this->table,
                array(
                    'followers' => json_encode( $followers )
                ),
                array( 
                    'user_id' => $args["user_id"]
                ),
                "%s",
                "%d"
            );

            return $updated;
        }
    }
}

new TestThis();

我用这个jQuery代码测试了它: *应该存在跟随ID 2的用户,或者我们应该将用户名发送到add_followed_by函数。

jQuery.post(ajaxurl, { 'action' : "add_follower", "user_to_follow" : 2 }, function() {
    console.log( "listo" );
}).fail(function(err) { console.log(err); })

如果您有疑问,请告诉我。

更新:取消关注的代码。

if( ( $key = array_search( $args['unfollow_to'], $following ) ) !== false ) {
    unset( $following[$key] );
    reset( $following );

    $updated = $wpdb->update( $this->table,
        array(
            'following' => json_encode( $following )
        ),
        array( 
            'user_id' => $args['user_id']
        ), 
        '%s', '%d'
    );

    return $updated;

}

答案 1 :(得分:0)

取消关注选项如下所示:

更新: 这应该有用。

liftIO

这是因为您要通过if( ( $key = array_search( $args['unfollow_to'], $following ) ) !== false ) { unset( $following[$key] ); reset( $following ); $updated = $wpdb->update( $this->table, array( 'following' => json_encode( $following ) ), array( 'user_id' => $args['user_id'] ), '%s', '%d' ); return $updated; } 删除,而应该由key代替。