首页 > 解决方案 > 在 laravel7 中使用关系获取数据时出现问题

问题描述

我有三个表国家,州,customer_contacts。我想将所有客户详细信息显示到列表视图结构中。但在我的客户表中,只有国家和州的 id 分别保存。我想从其他两个表中获取 Country nad state Name 。表结构如下:

1. 国家

id  name
1  India
2  Canada

2. 状态

id  name     country_id
1  Mumbai       1
2  Delhi        1
3  abc          2
4  xyz          2

3. 客户联系方式

id  c_name     country_id  state_id
1   abcdee       1           2
2   xyzerr       1           1
3   extraa       2           3
4   newsss       2           4

我想用国家名称和州名获取客户名称。

我正在使用以下查询来获取数据,但仅获取 customer_contact 数据如何使用任何查询或关系获取名称。

$data = CustomerContact::with('Country', 'State')->get();

我使用的关系如下:

1) 国家模式

<?php

   namespace App;

   use Illuminate\Database\Eloquent\Model;

  class Country extends Model
   {

   public function state()
   {
         return $this->hasMany(State::class);
  }
  public function customercontact()
  {
       return $this->hasMany(CustomerContact::class);
  }
}

2) 状态模型

class State extends Model
{
  public function customercontact()
  { 
       return $this->hasMany(CustomerContact::class);
  }
  public function country()
  {
       return $this->belongsTo(Country::class);
  }
}

3) 客户联系方式

 use Illuminate\Database\Eloquent\Model;

    class CustomerContact extends Model
    {
          protected $guarded = [];

       public function country()
       {
           return $this->belongsTo(Country::class);
       }

       public function state()
        {
            return $this->belongsTo(State::class);
        }
  } 

             
             

我想在列表视图中显示数据,例如 CustomerName、CountryName、StateName。当我做 dd($data)

获取具有国家和州 ID 的数据,但关系获取空值。

在这方面帮助我。

标签: laravellaravel-7

解决方案


CustomerSupport上,您定义了两个函数country()state(),因此您的代码将是:

$data = CustomerContact::with('country','state')->get();

或者,

$data = CustomerContact::with('country')->with('state')->get();

推荐阅读