首页 > 解决方案 > 在 Laravel 的 index.blade 中使用多态关系

问题描述

在此之前,我不使用多态关系。我只user_id用于每个表,例如 Admin、Buyer 和 Contractor,以将其与 User 表相关联。现在,我可以使用多态关系,因为我需要在导航栏中使用nameavatar3 个表中的列。每次用户登录他们的帐户时,他们都会在导航栏上看到他们的姓名和头像。

用户表

id
role
email
typable_id
typable_type

买家表

id 
name
address
phone_no
email
avatar

用户.php

public function typable()
    {
        return $this->morphTo();
    }

买家.php

public function user()
    {
        return $this->morphMany(User::class, 'typable');
    }

这已经解决了我的问题。但现在的问题是,如何为我的索引视图使用多态关系?这是我使用 user_id 时使用的上一个查询。

买家控制器.php

public function index(Request $request)
    {
        if(Auth::user()->role == 'buyer')
            {     
                $buyers = Buyer::where('user_id', '=', Auth::id())->first();
                return view('buyers.index',['buyer'=>$buyers]);
            }
    }

index.blade.php

<div class="profile-main">
    <img src="http://localhost:8000/storage/images/{{auth()->user()->typable->avatar}}" width="100" length="100" class="img-circle" alt="Avatar">
    <h3 class="name">{{$buyer->name}}</h3>
</div>

<div class="profile-detail">
   <div class="profile-info">
       <h4 class="heading"><b><center>Resident's Details</center></b></h4>
           <ul class="list-unstyled list-justify">
               <li><b>Buyer ID: </b>{{$buyer->buyer_id}}</li>
               <li><b>Name: </b>{{$buyer->name}}</li>
               <li><b>Address: </b>{{$buyer->address}}</li>
               <li><b>Phone Number: </b>{{$buyer->phone_no}}</li>
               <li><b>Email: </b>{{$buyer->email}}</li>
            </ul>
    </div>
<div class="text-center"><a href="/buyer/{{$buyer->id}}/edit" class="btn btn-primary">Edit Profile</a></div>                       

当我使用买家帐户登录时,这是我得到SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause' (SQL: select * from 买家whereuser_id = 8 limit 1)Trying to get property 'name' of non-object.

标签: phpmysqllaravelrelationship

解决方案


试试这个:


$buyers = Buyer::find(Auth::user()->typable_id);

推荐阅读