我在数据库中有一个名为'User'的表。我想要的只是获取用户的基本信息。我试图从数据库中获取数据,但让我烦恼的是我获取了表中的所有数据。
UserTable
|id|username|firstname|lasttname|middlename|gender|age|birthdate|address|contact_number|designation|
1 admin lee chiu kim male 47 07-22-87 cebu 0977452445 admin
2 lrose rose loo mar female 27 04-02-88 cebu 0977452445 manager
3 mgray gray men try male 37 01-22-89 cebu 0977452445 employee
UserProfile.php
- >模型
<?php
class UserProfile extends Eloquent {
public $timestamps=false;
protected $table = 'users';
protected $fillable=array('firstname','lastname', 'middlename', 'gender', 'age', 'birthdate', 'address', 'contact_number', 'designation');
}
这是我网站的模型。
UserProfileContoller.php
- &gt;控制器
<?php
class UserProfileController extends \BaseController {
public function index($id)
{
$userprofile = User::find($id);
return View::make('userprofile.index', array('userprofile' => $userprofile));
//return View::make('userprofile.index')->with('UserProfiles',UserProfile::get());
}
例如,我目前登录用户名admin,我想编辑和查看我的个人资料。如何仅为管理员获取数据。请帮助。
她的情况是这样的。假设他们有3名员工。所以在表3中的用户名。我假设我不是管理员。我将使用lrose登录。另一个以admin和so.on登录如果我们三个人将转到我们的个人资料,唯一显示的是他们自己的个人资料并可以编辑它。
答案 0 :(得分:2)
假设您为数据库设置属性,为什么不使用DB
对象?
// In the User table find the item with the username 'admin'
DB::table('User')->where('username', '=', 'admin')->get();
获取某些已登录用户的信息(假设您拥有其用户名),称为$userprofile
。然后我们需要做的就是find
按ID然后获取username
:
// $id is the ID of the logged in user
$userprofile = User::find($id)->username; // get username of logged in user
答案 1 :(得分:0)
$ userprofile :: find($ id)只会获取admin的信息,如果$ id = 1。
find()只返回数据库中的1个元组。
调用find()后,您可以访问数据:
$userprofile->firstname
答案 2 :(得分:0)
你的意思是当你将$ id传递给用户控制器的索引方法时,会返回其他用户的所有数据吗?
这有点奇怪。
希望这有帮助。
答案 3 :(得分:0)
首先,您需要在登录后使用Session
并将id
用户名存储在会话中。
e.g。
第1步:
if($login) //successfull login
{
Session::put('userid', $userid);
//this id, you have to retreive it from the database after successful login
}
第2步:
设置route
Route::get('profile',['uses' => 'UserProfileContoller@index']);
第3步:
控制器的
public function index()
{
if(is_null(Session::get('userid'))) return Redirect::to('login');
return View::make('userprofile.index', ['userprofile' => $this->model->index()]);
// Above code uses dependency injection to retrieve the information from db.
}
第4步:
UserProfileModel
public function index()
{
return DB::table('user')->where('id','=', Session::get('userid'))->first();
}
p.s. i find it easier to use query builder than eloquent orm. if you want to use orm, change the code where needed.