php - 在 Laravel 的 index.blade 中使用多态关系
问题描述
在此之前,我不使用多态关系。我只user_id
用于每个表,例如 Admin、Buyer 和 Contractor,以将其与 User 表相关联。现在,我可以使用多态关系,因为我需要在导航栏中使用name
这avatar
3 个表中的列。每次用户登录他们的帐户时,他们都会在导航栏上看到他们的姓名和头像。
用户表
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
买家where
user_id = 8 limit 1)
和Trying to get property 'name' of non-object
.
解决方案
试试这个:
$buyers = Buyer::find(Auth::user()->typable_id);
推荐阅读
- docker - 使用 docker-compose.yml 绑定挂载时如何解决错误?
- javascript - React JS - 我无法在“选择”的选定选项中提供 console.log
- c# - 即使捕获到异常,是否有任何方法可以找到 .net 应用程序崩溃的原因
- angular - 无法找到解决方案,尝试注册减速器编译错误...类型“Action”不可分配给类型“Actions”
- google-sheets-formula - 带有 UTC 时间戳的 Google 表格 Countif 函数
- php - 在 laravel 上比较来自 db 的日期使用 sql
- mysql - Django中的SQL instr等价物
- mule - Mule 4.3 社区版的可重复文件存储流
- c# - Navisworks,如何获得有关 ModelItemCollection 的位置
- c# - 同时在 2 个不同的环境(DEV 和 STaging)上运行测试,而这两个环境都有 2 个不同的 url