【问题标题】:Use polymorphic relation in index.blade in Laravel在 Laravel 的 index.blade 中使用多态关系
【发布时间】:2020-12-31 05:26:41
【问题描述】:

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

用户表

id
role
email
typable_id
typable_type

买家表

id 
name
address
phone_no
email
avatar

用户.php

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

Buyer.php

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

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

BuyerController.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 buyerswhereuser_id = 8 limit 1)Trying to get property 'name' of non-object 的错误。

【问题讨论】:

  • 什么是residential?您只为买方显示名为 user 的关系...并且来自 sql buyers 表的错误消息没有 user_id 列所以不确定您为什么要尝试使用该列
  • 你可以忽略住宅,因为这是我已经建立的另一种关系。对于错误user_id,这是因为我在 index.blade 中使用的查询是在我建立多态关系之前。现在我想知道如果我使用多态关系我应该在 index.blade 中做什么查询。

标签: php mysql laravel relationship


【解决方案1】:

试试这个:


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

【讨论】:

    猜你喜欢
    • 2019-01-22
    • 2017-05-31
    • 1970-01-01
    • 2019-02-02
    • 2016-08-30
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    相关资源
    最近更新 更多