【问题标题】:How to show name from id using relationship in laravel 5.6?如何在 laravel 5.6 中使用关系显示来自 id 的名称?
【发布时间】:2019-02-03 00:19:35
【问题描述】:

我想在表格中显示 rta 名称,但它给了我错误

发行人模型功能

public function rtalist(){
    return $this->belongsTo('App\RTAList','rta_id','id');
}

RTAList 模型

protected $table = 'rta_list';
protected $fillable = ['rta_name','dp_type','rta_address','rta_phone','rta_email','dp_status','setup_date'];

发行者控制器中的代码

 $data = Issuer::with('rtalist')->get();
    return view('admin.issuer.view_all_issuer')->with(compact('data'));

在 view_issuer.blade.php 中

  <td style="text-transform: uppercase;">{{ $issuers->rta_list->rta_name }}</td>

但它给了我这个错误 SQLSTATE [42S22]:找不到列:1054 'where 子句'中的未知列'rta_list.id'(SQL:select * from rta_list where rta_list.id in (3, 4))

如何解决这个问题并显示名称而不是 id..

【问题讨论】:

  • RTAList Model的主键是什么?

标签: php laravel laravel-5


【解决方案1】:

问题是您在 rta_list 表中没有名称为 id 的主键。您必须具有如下结构

发行人表

id --primary_id
rta_list_id --foreign_key
.
.
....

RTAList 表

p_id --primary_id
rta_name
.
.
....

现在建立如下关系

public function rtalist(){
    return $this->belongsTo('App\RTAList', 'rta_list_id', 'p_id');
}

【讨论】:

    【解决方案2】:

    删除参数“id”并在第二个参数中添加“your_compost_table_name”:

    public function rtalist(){
      return $this->belongsTo('App\RTAList', 'your_compost_table_name', 'rta_id');
    }
    

    或尝试:

    public function rtalist(){
      return $this->belongsTo('App\RTAList', 'rta_id');
    }
    

    【讨论】:

      【解决方案3】:

      你们的关系应该是这样的

      public function rtalist(){
          return $this->belongsTo('App\RTAList','rta_list_table_primary_key','Issuer Model table foreign key');
      }
      

      它应该可以工作。

      【讨论】:

        猜你喜欢
        • 2021-12-25
        • 1970-01-01
        • 2019-03-10
        • 2018-08-22
        • 2018-07-27
        • 2019-03-07
        • 2018-12-21
        • 2018-11-30
        • 1970-01-01
        相关资源
        最近更新 更多