如何从Laravel中的对象获取用户名

时间:2019-05-21 17:14:50

标签: php laravel laravel-5

我是Laravel的初学者,以下是我的移民。

Schema::create('users', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->bigInteger('company_id')->unsigned();
    $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
    $table->boolean('enable')->default(0);
    $table->string('name', 120)->nullable();
    $table->string('surname', 120)->nullable();
    $table->string('email', 120)->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->boolean('enable_map')->default(0);
    $table->rememberToken();
    $table->timestamps();
    $table->engine = "InnoDB";
});

Schema::create('comments', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->bigInteger('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->Integer('rating');
    $table->text('content');
    $table->dateTime('date_time');
    $table->string('ip', 25);
    $table->engine = "InnoDB";
});

User.php

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use psCMS\Presenters\UserPresenter;

    public static $roles = [];

    protected $fillable = ['company_id', 'enable', 'name', 'surname', 'email', 'email_verified_at', 'password', 'counter', 'url_address',  'isCompany', 'isMailing', 'content', 'nip1', 'business1', 'phone1', 'street1', 'number1', 'postal_code1', 'city1', 'country_id1', 'provincial_id1', 'nip2', 'business2', 'phone2', 'street2', 'number2', 'postal_code2', 'city2', 'country_id2', 'provincial_id2', 'nip3', 'business3', 'phone3', 'street3', 'number3', 'postal_code3', 'city3', 'country_id3', 'provincial_id3', 'cash', 'lng', 'lat', 'enable_map', 'remember_token', 'created_at', 'updated_at', 'last_login_at', 'last_login_ip' ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function photos()
    {
        return $this->morphMany('App\Photo', 'photoable');
    }

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

    public function comments()
    {
        return $this->hasMany('App\Comments');
    }

    public function hasRole(array $roles)
    {
        foreach($roles as $role)
        {
            if(isset(self::$roles[$role]))
            {
                if(self::$roles[$role])  return true;

            } else {
                self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                if(self::$roles[$role]) return true;
            }

        }

        return false;
    }

    public function loginHistory()
    {
        return $this->hasMany('App\UserLoginHistory');
    }
}

Comments.php

class Comments extends Model
{
    protected $quarded = [];
    public $timestamps = false;

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

当我编写此代码时:

Comments::where('content','LIKE','%'.$query.'%')->orWhere('id','LIKE','%'.$query.'%')->orderBy($sortColumn, $sortMethod)->paginate(25);

我没有有关该用户的信息。我只有评论中的值。为什么我如何获取有关用户的信息,并添加这些评论?我想显示评论列表以及有关用户的信息。

3 个答案:

答案 0 :(得分:2)

  

我没有有关用户的信息。我只有评论中的值。为什么?

因为您仅在模型注释上进行查询

  

如何获取有关用户的信息,并添加评论?

与用户一起添加到查询中:

$comments_with_user_info = Comments::with('user')->where('content','LIKE','%'.$query.'%')->orWhere('id','LIKE','%'.$query.'%')->orderBy($sortColumn, $sortMethod)->paginate(25);
  

我想显示评论列表以及有关用户的信息。

您可以通过这种方式获取名称(例如在Blade中):

@foreach($comments_with_user_info as $comment)
    {{ $comment->user->name }}
@endforeach

答案 1 :(得分:2)

  1. 作为最佳实践,类名应采用表名的单数形式。您可以在https://laravel.com/docs/5.8/eloquent#defining-models上了解此内容。

  2. 您应该能够通过急切地使用user()加载with()关系。

$comments = Comments::with('user')
                ->where('content','LIKE','%'.$query.'%')
                ->orWhere('id','LIKE','%'.$query.'%')
                ->orderBy($sortColumn, $sortMethod)->get();

                // or paginate method

  1. 您要检索的是一个集合。因此,您将不得不遍历comments以获得user对象
foreach($comment in $comments){
    $userObj = $comments->user;
    $email = $userObj->email;
    //...etc here
}

答案 2 :(得分:0)

注释:: with('user')-> where('content','LIKE','%'。$ query。'%')-> orWhere('id','LIKE','%' 。$ query。'%')-> orderBy($ sortColumn,$ sortMethod)-> paginate(25);