使用laravel7中的关系获取数据时出现问题
我有三个国家、州、客户联系人。我希望将所有客户详细信息显示到列表视图结构中。但在我的客户表中,仅分别保存国家和州的id。我想从另外两个表中获取国家和州名称。 表结构如下: 1。国家使用laravel7中的关系获取数据时出现问题,laravel,laravel-7,Laravel,Laravel 7,我有三个国家、州、客户联系人。我希望将所有客户详细信息显示到列表视图结构中。但在我的客户表中,仅分别保存国家和州的id。我想从另外两个表中获取国家和州名称。 表结构如下: 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 coun
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
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);
}
}
我想获取带有国家名称和州名称的客户名称
我使用下面的查询获取数据,但仅获取客户联系数据。如何使用任何查询或关系获取姓名
$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);
}
}
class State extends Model
{
public function customercontact()
{
return $this->hasMany(CustomerContact::class);
}
public function country()
{
return $this->belongsTo(Country::class);
}
}
3)客户联系
id c_name country_id state_id
1 abcdee 1 2
2 xyzerr 1 1
3 extraa 2 3
4 newsss 2 4
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(数据)
正在获取具有国家和州id但关系获取空值的数据
请帮助我。在CustomerSupport上,您定义了两个函数
country()
和state()
,因此您的代码将是:
$data = CustomerContact::with('country','state')->get();
或者
我觉得你的亲戚有点奇怪。顾客有许多州,而国家有许多州@FedericoProvenziani,这是一种联系方式。在联系人表单国家和州下拉字段中。好的,但我的意思是:客户将在一个国家(即一个州)填写联系人表单。或者我遗漏了什么?是的,对。客户可以在表格中填写姓名、国家和相应的州的详细信息。我尝试了此操作,但在州和国家关系中得到空值。您有一个带有('country','state')的打字错误
将带有('country','state')$data=CustomerContact::with('country','state')->get();我正在用这个。但在关系中获取空数据。您在迁移文件中正确定义了外键吗?您能帮我吗?