如何获取laravel7中的三张表数据
How to get three tables data in laravel7
我有三个 table 国家,州,customer_contacts。
我想将所有客户详细信息显示到列表结构中。但是在我的客户中 table 分别只保存国家和州的 ID。
Table结构如下:
国家
id name
1 India
2 Canada
州
id name country_id
1 Mumbai 1
2 Delhi 1
3 abc 2
4 xyz 2
Customer_contact
id c_name country_id state_id
1 abcdee 1 2
2 xyzerr 1 1
3 extraa 2 3
4 newsss 2 4
我想获取带有国家名称和州名称的客户名称。
我正在使用以下查询来获取数据,但仅获取客户联系数据如何通过任何查询或关系获取姓名。
$data = CustomerContact::latest()->get();
如果有任何解决方案,请告诉我
你们两个在这里有机会:
首先,您可以使用 relationships:
CustomerContact 模型
country()
{
return $this->belongsTo(Country::class);
}
国家模式
state()
{
return $this->belongsTo(State::class);
}
使用这样的关系:
$data = CustomerContact::with('country.state')->latest()->get();
第二个选项是使用 join()
:
CustomerContact
::join('countries', 'countries.id', 'customer_contact.country_id')
->join('states', 'states.id', 'countries.state_id')
->latest()
->get();
我有三个 table 国家,州,customer_contacts。 我想将所有客户详细信息显示到列表结构中。但是在我的客户中 table 分别只保存国家和州的 ID。 Table结构如下:
国家
id name
1 India
2 Canada
州
id name country_id
1 Mumbai 1
2 Delhi 1
3 abc 2
4 xyz 2
Customer_contact
id c_name country_id state_id
1 abcdee 1 2
2 xyzerr 1 1
3 extraa 2 3
4 newsss 2 4
我想获取带有国家名称和州名称的客户名称。
我正在使用以下查询来获取数据,但仅获取客户联系数据如何通过任何查询或关系获取姓名。
$data = CustomerContact::latest()->get();
如果有任何解决方案,请告诉我
你们两个在这里有机会:
首先,您可以使用 relationships:
CustomerContact 模型
country()
{
return $this->belongsTo(Country::class);
}
国家模式
state()
{
return $this->belongsTo(State::class);
}
使用这样的关系:
$data = CustomerContact::with('country.state')->latest()->get();
第二个选项是使用 join()
:
CustomerContact
::join('countries', 'countries.id', 'customer_contact.country_id')
->join('states', 'states.id', 'countries.state_id')
->latest()
->get();