首页 > laravel新手获取单行数据问题

laravel新手获取单行数据问题

获取单行数据,却返回如何这么多的数据


自己的代码

public function index(){
    var_dump(AdminUser::find(1));
    return view('admin.sign.index');
}

模型定义

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class AdminUser extends Model
{
    protected $table='admin_user';

    //验证正好密码
    public function check_admin($username,$pwd){
        $admin_user=$this->where('username',$username)->select(['password'])->first();
        return $admin_user;
    }
}

返回的数据
`

object(AppAdminUser)#207 (24) { ["table":protected]=> string(10) "admin_user" ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["keyType":protected]=> string(3) "int" ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(5) { ["id"]=> int(1) ["username"]=> string(7) "xingren" ["password"]=> string(60) "$2y$10$h0t4Hu/d5xFWGz0nH3IjIeHyzNcjRjqn3i5W9dTGIvOQB5wtVeSHi" ["status"]=> int(1) ["create_time"]=> int(1483423452) } ["original":protected]=> array(5) { ["id"]=> int(1) ["username"]=> string(7) "xingren" ["password"]=> string(60) "$2y$10$h0t4Hu/d5xFWGz0nH3IjIeHyzNcjRjqn3i5W9dTGIvOQB5wtVeSHi" ["status"]=> int(1) ["create_time"]=> int(1483423452) } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["casts":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) }`


建议你用 dd(AdminUser::find(1)) 打印出来看看 这样看的结构很清晰


这就是单行数据,哪里不对吗,只是这些数据以对象的形式存在,如果你希望是数组的形式,需要跟toArray方法,如果是需要json,跟toJson方法。


$this->where('username',$username)->first(['password])

只能是这样查找单条记录的某个字段,以集合的形式返回。
不能像其他框架一样直接返回某个字段的字符串类型的值。
不过你可以处理一下,拿到这条记录后再返回这个字段的字符串类型。


返回AdminUser对象,就是你上面的
class AdminUser extends Model
这样你可以轻松的使用AdminUser自定义的和继承自Model的方法
Model中已经定义了__get__set
如果你只是需要获取属性也可以像普通对象一样直接$adminUser->id获取值。

laravel是很强大的,所以数据库的查询一般都不会直接返回一个普通的对象或者是数组,这些都是为了方便我们进行一些可能的后续操作。不要一开始就被他吓到就好,用多了你就会发现真的很爽~!


这就是单行数据,因为用了first(),不过数据比较多而已。
如果只需要某列数据可用first('列名')

【热门文章】
【热门文章】