它只显示第一个数据。如何显示具有相同ID的每个数据?

时间:2016-10-22 03:39:32

标签: php laravel

此代码仅显示找到的 // In app.js: var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var expressValidator = require('express-validator'); var cookieParser = require('cookie-parser'); var session = require('express-session'); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var bodyParser = require('body-parser'); var multer = require('multer'); var uploads = multer({dest: './uploads'}); var flash = require('connect-flash'); var mongo = require('mongodb'); var mongoose = require('mongoose'); var db = mongoose.connection; var routes = require('./routes/index'); var users = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // Handle file uploads var upload = multer({ dest: './uploads' }); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // Handle Express Sessions app.use(session({ secret:'secret', saveUninitialized: true, resave: true })); // passport app.use(passport.initialize()); app.use(passport.session()); // Validator app.use(expressValidator({ errorFormatter: function(param, msg, value) { var namespace = param.split('.') , root = namespace.shift() , formParam = root; while(namespace.length) { formParam += '[' + namespace.shift() + ']'; } return { param : formParam, msg : msg, value : value }; } })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(flash()); app.use(function (req, res, next) { res.locals.messages = require('express-messages')(req, res); next(); }); app.get('*', function(req, res, next){ res.locals.user = req.user || null; next(); }); app.use('/', routes); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); <!-- begin snippet: js hide: false console: true babel: false -->数据。

    // In users.js in routes:

    var express = require('express');
    var router = express.Router();
    var passport = require('passport');
    var LocalStrategy = require('passport-local').Strategy;
    var User = require('../models/user');
    var multer = require('multer');
    var uploads = multer({dest: './uploads'});
    /* GET users listing. */
    router.get('/', function(req, res, next) {
      res.send('respond with a resource');
    });

    router.get('/register', function(req, res, next) {
      res.render('register', {
          'title': 'Register'
      });
    });

    router.get('/login', function(req, res, next) {
      res.render('login', {
          'title': 'Login'
      });
    });

    router.post('/register', uploads.single('profileimage'), function(req, res, next) {
        var name = req.body.name;
        var email = req.body.email;
        var username = req.body.username;
        var password = req.body.password;
        var password2 =  req.body.password2;


        // Check for Image Field
        if (req.file) {
            console.log('uploading File...');

            // File Info
            var profileImageOriginalName = req.files.profileimage.originalname;
            var profileImageName = req.files.profileimage.name;

            var profileImageMime = req.files.profileimage.mimetype;
            var profileImagePath = req.files.profileimage.path;
            var profileImageExt = req.files.profileimage.extension;
            var profileImageSize = req.files.profileimage.size;
        } else {
            // Set a Default Image
            var profileImageName = 'noimage.png';
        }

        // Form Validation

        req.checkBody('name','Name field is required').notEmpty();
        req.checkBody('email','Email field is required').notEmpty();
        req.checkBody('email','Email not valid').isEmail();
        req.checkBody('username','Username field is required').notEmpty();
        req.checkBody('password','Password field is required').notEmpty();
        req.checkBody('password2','Password do not match').equals(req.body.password);

        // Check for errors
        var errors = req.validationErrors();

        if(errors){
            res.render('register', {
                errors: errors,
                name: name,
                email: email,
                username: username,
                password: password,
                password2: password2
            });
        } else {
            var newUser = new User({
                name: name,
                email: email,
                username: username,
                password: password,
                profileImage: profileImageName
            });

                // Create User
                User.createUser(newUser, function(err, user){
                    if(err)throw err;
                    console.log(user);
                });

                //Success Message
                req.flash('success', 'You are now registered and may log in');

                res.location('/');
                res.redirect('/');
        }
    });

    passport.serializeUser(function(user, done) {
      done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
      User.getUserById(id, function(err, user) {
        done(err, user);
      });
    });

    passport.use(new LocalStrategy(
        function(username, password, done){
            User.getUserByUsername(username, function(err, user){
                if(err) throw err;
                if(!user){
                    console.log('Unknown User');
                    return done(null, false, {message: 'Unknown User'});
                }

                User.comparePassword(password, user.password, function(err, isMatch){
                    if(err) throw err;
                    if(isMatch){
                        return done(null, user);
                    } else {
                        console.log('Invalid Password');
                        return done(null, false, {message: 'Invalid Password'});
                    }
                });
            });
        }
    ));

    router.post('/login', passport.authenticate('local',{failureRedirect: '/users/login', failureFlash: 'Invalid username or password'}), function(req, res){
        console.log('Authentication Successful');
        req.flash('success', 'You are logged in');
        res.redirect('/');
    });

    router.get('/logout', function(req, res){
        req.logout();
        req.flash('success', 'You have logged out');
        res.redirect('/users/login');
    });

    module.exports = router;

// In package.json: { "name": "nodeauth", "version": "1.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "~1.15.1", "cookie-parser": "~1.4.3", "debug": "~2.2.0", "express": "~4.13.4", "jade": "~1.11.0", "morgan": "~1.7.0", "serve-favicon": "~2.3.0", "mongodb":"*", "mongoose":"*", "connect-flash":"*", "express-validator":"*", "express-session":"*", "express-messages":"*", "passport":"*", "passport-local":"*", "passport-http":"*", "multer":"*" } }

    // In user.js in models:

    var mongoose = require('mongoose');
    var bcrypt = require('bcrypt');

    mongoose.connect('mongodb://localhost/nodeauth');

    var db = mongoose.connection;

    // User Schema
    var UserSchema = mongoose.Schema({
        username: {
            type: String,
            index: true
        },
        password: {
            type: String,
            required: true,
            bcrypt: true
        },
        email: {
            type: String
        },
        name: {
            type: String
        },
        profileimage: {
            type: String
        }

    });

    var User = module.exports = mongoose.model('User', UserSchema);

    module.exports.comparePassword = function(candidatePassowrd, hash, callback){
        bcrypt.compare(candidatePassowrd, hash, function(err, isMatch){
            if(err) return callback(err);
            callback(null, isMatch);
        });
    }

    module.exports.getUserById = function(id, callback){
        User.findById(id, callback);
    }

    module.exports.getUserByUsername = function(username, callback){
        var query = {username: username};
        User.findOne(query, callback);
    }

    module.exports.createUser = function(newUser,callback){
        bcrypt.hash(newUser.password, 10, function(err, hash){
            if(err) throw err;

            // Set Hashed password
            newUser.password = hash;

            // Create User
            newUser.save(callback);
        });
    };

first

public function getGroupInfo($eg_id){
        $members = \App\EventGroupMembers::where('eg_id', '=', $eg_id)->get();
        if ($members->count() > 0) {
            $user = \App\User::find($members[0]->user_id);
            echo $user->first_name;
        } else {
            return false;
        }
    }

我该怎么做才能显示所有event_group_members具有相同的eg_id user_id 1 1 2 2 2 3 3 4 3 5

3 个答案:

答案 0 :(得分:1)

试试这个:

foreach($members as $member)
{
    echo $member->id;
    // It will echo diff id for each iteration
}

说明:$ member是一个具有多个值的Std类对象,如果您使用它:

$members[0]->user_id;

表示您正在引用其第0个索引值。要访问所有值,您必须使用循环。

答案 1 :(得分:0)

你可以这样做

 public function getGroupInfo($eg_id){
        $userNames = array();
        $members = \App\EventGroupMembers::where('eg_id', '=', $eg_id)->get();
        if ($members->count() > 0) {
        foreach($members as $data){
        $user = \App\User::where('user_id',$data->user_id)->get();

        foreach($user as $userData){
        $userNames[] = $userData->first_name;
        }
        }         
            } else {
                return false;
            }
        }

然后您可以从该阵列中检索用户名。

foreach($userNames as $name){
echo $name;
} 

答案 2 :(得分:0)

您在user_id模型中有EventGroupMembers,因此您似乎正在使用已在EventGroupMembersUser模型之间{{}}}的应用。因此,请在event_group_members模型中的User表格迁移和关系中查看one-to-many relationship

public function eventGroupMembers()
{
    return $this->belongsTo('App\User');
}

之后,您可以按eg_id型号中的EventGroupMembers过滤用户:

$members = User::with(['eventGroupMembers' => function($q) use ($eg_id) {
    $q->where('eg_id', $eg_id);
})->get();

此解决方案只对数据库执行两次查询。

然后只列出用户&#39;刀片模板中的名字:

@foreach ($members)
    $member->first_name;
@endforeach