试图获取非对象的属性 - 名称

时间:2021-06-19 02:53:40

标签: laravel laravel-5 eloquent laravel-8

我正在尝试打印用户名,但出现错误

<块引用>

试图获取非对象的属性

模型

用户

<?php

namespace App\Models;
use App\Models\Registro;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

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

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
    public function registros(){
      
       
         return $this->belongsTo('\App\Models\Registro', 'user_id');
    }
}

注册

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use \App\Models\User;

class Registro extends Model
{
    use HasFactory;

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

    }
   
}

数据库:

enter image description here

在blade.php中:

  {{$registro->user_id->name}}  

也许我在人际关系上做错了什么,但我自己无法弄清楚

<tbody class="list">
            @foreach($registros as $registro)
              <tr>
                <th scope="row">
                  <div class="media align-items-center">
                    <a href="#" class="avatar rounded-circle mr-3">
                      <img alt="Image placeholder" src="../../assets/img/theme/bootstrap.jpg">
                    </a>
                    <div class="media-body">
                      <span class="name mb-0 text-sm">{{$registro->user_id->name}}</span>
                    </div>
                  </div>
                </th>
            
              </tr>
             @endforeach
            </tbody>

尝试改变关系,但不起作用 不允许我打印 user_id 的名称,请帮助

2 个答案:

答案 0 :(得分:3)

您错误地访问了用户详细信息。应该是

{{$registro->user->name}}

这里的 user 是在 relationship 模型中定义的 Registro 名称

答案 1 :(得分:0)

您的关系是 hasMany 用户,因此当您访问它时,您将获得一个集合。通过这种方式,您需要循环该集合以获得所需的用户模型