尝试使用MODELS获取用户名但收到此错误:尝试获取非对象的属性

时间:2017-01-19 11:33:10

标签: php database model laravel-5.2 laravel-migrations

错误: ErrorException in 814a6fb85b2cceb262c3a8191c08e42742940fc7.php line 223: Trying to get property of non-object (View: /var/www/html/m/TS/resources/views/d/show-details.blade.php)

其实我正在尝试获取将结果存储在数据库中的用户名TN has got user_id as a foreign key in the table,因此我需要使用usernameuser_id获取models but I am getting this problem尝试获取与id关联的非对象when I try to get the用户名的属性。我不知道我做错了什么。

我在这里的错误value="{{$tn->users->username}}"在CACHED文件中显示。

我也在下面给出了我的代码。

提前谢谢

控制器

public function details($id) {

        $d= $this->detail->showDetails($id);
        $tn= TN::find($id);

// calling functions from Model
        $n = $d->tN;
        $o = $d->tO;

return view('details.show-details', compact('d','o', 'n', 'tn'));

}

查看

foreach($n as $n)
<input style="font-size:10px;font-weight: bold; color:black; background:#59d864;" value="{{$tn->users->username}}" readonly>

模型

用户模型

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use App\TN;
use App\TO;
use App\UserType;

class User extends Authenticatable
{
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'username', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

public function tN() {
    return $this->hasMany(TN::class);
}

public function tO() {
    return $this->hasMany(TO::class);
}

public function userType() {
    return $this->belongsTo(UserType::class);
}

}

TO Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\D;
use App\TT;
use App\User;

class TO extends Model
{
protected $fillable = ['o', 'date'];

public function d() {
    return $this->belongsTo(D::class);
}

public function tOType() {
    return $this->belongsTo(TOType::class);
}

public function users() {
    return $this->belongsTo(User::class);
}
}

TN模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Debtor;
use App\TracingType;
use App\User;

class TN extends Model
{
protected $fillable = ['r', 'date'];

public function d() {
   return $this->belongsTo(D::class);
}

public function tType() {
    return $this->belongsTo(TType::class);
}

public function users() {
    return $this->belongsTo(User::class);
}

}

1 个答案:

答案 0 :(得分:0)

您好我已经对这个问题进行了排序但是忘了在这里发布问题就在这里

public function users() {
    return $this->belongsTo(User::class);
}

这应该是public function user()而不是users。因为belongsToUser类,它应该是单数而不是复数,而hasMany我们使用复数。谢谢你的帮助,虽然...... :)