laravel - 在 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 的数据,但关系获取空值。
在这方面帮助我。
解决方案
在CustomerSupport上,您定义了两个函数country()
和state()
,因此您的代码将是:
$data = CustomerContact::with('country','state')->get();
或者,
$data = CustomerContact::with('country')->with('state')->get();
推荐阅读
- java - 如何在 Java 中为无参数构造函数编写 Junit 测试?
- objective-c - Objective-C Clang-Format 方法大括号中断
- gerrit - 如何使用 cmd + F 在 Gerrit 审阅中进行文本搜索?
- php - 尽管使用会话登录,但不会自动进入第二页
- javascript - 如何在 vue.js 中读取 json 文件
- android - xamarin android中的按钮对齐
- proof - 需要证明语言 L = {a^nb^m: n < m < 2m} 不是正则的
- python - 从内部房间预订网站抓取数据
- oracle - 如何按结果将分组保存到oracle中的变量或另一个表?
- postgresql - PostgreSQL 中不存在 double 类型