Laravel关系归属于错误试图获取非对象的属性“名称”

时间:2019-05-01 03:14:30

标签: laravel

我遇到错误,尝试在我的视图中打印与实体(模型)机构建立的belongsTo关系的属性名称时,试图获取非对象的属性“名称”,这是最有趣的事情是我对用户关系做了同样的事情,并且奏效了。

我已经尝试了几种解决方案,这些解决方案在堆栈溢出中都没有,但是都没有得到结果,这似乎很简单,但是...不起作用

模型机构

class Institution extends Model implements Transformable
{

    use TransformableTrait;

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

    public $timestamps = true;
}

模型用户

class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    public $timestamps = true;

    protected $table = 'users';

    protected $fillable = [
        'cpf',
        'name',
        'phone',
        'birth',
        'gender',
        'notes',
        'email',
        'password',
        'status',
        'permission'
    ];

组实体

class Group extends Model implements Transformable
{
    use TransformableTrait;

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

    // a classe grupo pertence ao usuario atraves do metodo owneruser e institution
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function institution()
    {
        return $this->belongsTo(Institution::class);
    }

}

GroupsController

    public function index()
    {

        $groups = $this->repository->all();
        $user_list = $this->userRepository->selectBoxList();
        $institution_list = $this->institutionRepository->selectBoxList();

        return view('group.index', [
            'groups' => $groups,
            'user_list' => $user_list,
            'institution_list' => $institution_list
        ]);
    }

查看组

@foreach($groups as $group)
<tr>
    <td>{{ $group->id }} </td>
    <td>{{ $group->name }} </td>

    // In this line where the error
    // Trying to get property 'name' of non-object  occurs
    <td> {{$group->institution->name }} </td>
    // This line is working
    <td> {{ $group->user->name }} </td>

    <td>
        {!! Form::open(['route' => ['group.destroy', $group->id], 'method' => 'delete']) !!}
            {!! Form::submit("Remover") !!}
        {!! Form::close() !!}
    </td>
</tr>
@endforeach

我希望<td>{{ $group-> institution-> name }}</ td>中的输出 通过外键将组关联到的机构名称,它会返回错误。

1 个答案:

答案 0 :(得分:1)

从数据库映像中,我看到您在为外键Institution_id使用大写字母,而在其他地方使用小写字母。我相信它区分大小写,因此请在您的Group模型中尝试以下操作:

public function institution()
{
    return $this->belongsTo(Institution::class, 'Institution_id');
}

并在fillable列表中进行更改。