Uninote
Uninote

一些代码片段,全关联

模型相关

//文章表
public function comment()
{
	return $this->hasMany(FriendsComment::class, 'article_id', 'id');
}

public function resource()
{
	return $this->hasMany(FriendsResource::class, 'article_id', 'id');
}

public function user()
{
	return $this->belongsTo(User::class, 'uid', 'uid')->field(['uid', 'nickname']);
}

//评论表
public function reply()
{
	return $this->hasMany(FriendsReply::class, 'comment_id', 'id')->order('create_time');
}

public function user()
{
	return $this->belongsTo(User::class, 'from_id', 'uid')->field(['uid', 'nickname']);
}

//回复表
public function fromUser()
{
  return $this->belongsTo(User::class, 'from_id', 'uid')->field(['uid', 'nickname']);
}

public function toUser()
{
  return $this->belongsTo(User::class, 'to_id', 'uid')->field(['uid', 'nickname']);
}

数据展示

$data = FriendsArticle::with(
            [
                'user',
                'resource',
                'comment' => ['user', 'reply' => ['fromUser', 'toUser']],
            ]
        )->where('id', 1)->find()->toArray();

        if ($data['comment']) {
            foreach ($data['comment'] as $k => $comment) {
                if (isset($comment['reply']) && $comment['reply']) {
                    $tree = [];
                    $tree = $this->tree($comment['reply'], 0, $tree);//递归排序
                    $tree = array_filter(
                        $tree,
                        function ($row) {
                            return $row['is_delete'] == 0;
                        }
                    );//隐藏相关
                    $data['comment'][$k]['reply'] = $tree;
                }
            }
        }
        halt($data);
    }

    private function tree($arr, $pid = 0, &$tree = [])
    {
        foreach ($arr as $k => $v) {
            if ($v['pid'] == $pid) {
                $v['level'] = $level;
                $tree[] = $v;
                unset($arr[$k]);//已经判断过的元素可以再原始数组里删除 减少之后的判断次数
                $this->tree($arr, $v['id'], $tree);
            }
        }
        return $tree;
    }

powder使用

数据库

点赞(0) 阅读(1) 举报
目录
标题