使用 laravel7 中的关系获取数据时出现问题
Getting issue while fetching data using Relationship in laravel7
我有三个 table 国家,州 customer_contacts。我想将所有客户详细信息显示到列表视图结构中。但是在我的客户中 table 分别只保存了国家和州的 ID。我想从其他两个 table 获取 Country nad state Name 。
Table结构如下:
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。 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
我想获取包含国家名称和州名称的客户名称。
我正在使用下面的查询来获取数据,但只获取 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($数据)
获取具有国家和州 ID 的数据,但关系获取空值。
帮帮我。
在 CustomerSupport 上,您定义了两个函数 country()
和 state()
,因此您的代码将是:
$data = CustomerContact::with('country','state')->get();
或者,
$data = CustomerContact::with('country')->with('state')->get();
我有三个 table 国家,州 customer_contacts。我想将所有客户详细信息显示到列表视图结构中。但是在我的客户中 table 分别只保存了国家和州的 ID。我想从其他两个 table 获取 Country nad state Name 。 Table结构如下:
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。 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
我想获取包含国家名称和州名称的客户名称。
我正在使用下面的查询来获取数据,但只获取 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($数据)
获取具有国家和州 ID 的数据,但关系获取空值。
帮帮我。
在 CustomerSupport 上,您定义了两个函数 country()
和 state()
,因此您的代码将是:
$data = CustomerContact::with('country','state')->get();
或者,
$data = CustomerContact::with('country')->with('state')->get();