php - Laravel 雄辩的 ORM 关系
问题描述
我对 Eloquent ORM 关系有疑问,我有公司模型和国家模型,一对多关系,我使用了以下代码。
公司模式
class Company_model extends Model
{
public $table = "company";
public $primaryKey = "id";
public function countries(){
return $this->belongsTo('App\Models\Countries','country','countryId');
}
}
国家模式
class Countries extends Model
{
public $table = "countries";
public $primaryKey = "countryId";
}
我已使用以下代码检索要获取公司详细信息以及 countryName 的数据
$companyObj = new Company_model();
$result = $companyObj::with('countries')->get();
我得到了带有公司和国家详细信息的结果,但是国家详细信息以数组的形式出现,我需要它没有数组,我还需要使用国家名称,现在国家表中的所有详细信息都出现在数组中。
现在结果
Array ( [0] => Array ( [id] => 1 [companyName] => Test [address] => [country] => 1 [phone] => [email] => [website] => [companyImg] => 1 [create_by] => [create_time] => [countries] => Array ( [countryId] => 1 [countryName] => Test [currency] => [language] => ) ) )
我需要这样的结果
Array ( [0] => Array ( [id] => 1 [companyName] => Test [address] => [phone] => [email] => [website] => [companyImg] => 1 [create_by] => [create_time] => [countryName] => Test ) )
解决方案
您必须添加一个新方法,Company_model
该方法具有仅提供所选字段的方法。
class Company_model extends Model
{
public $table = "company";
public $primaryKey = "id";
public function countries(){
return $this->belongsTo('App\Models\Countries','country','countryId');
}
}
这是新方法。
public function countriesIDs()
{
return $this->belongsTo('App\Models\Countries')->select(['name']);
}
推荐阅读
- javascript - TypeError:无法读取 node.js 中未定义上传文件的属性“名称”
- python - 如何检查字典中是否存在具有特定模式的值?
- c# - 如何创建一个三列图表?
- python - 为什么我在保存文件时收到 Errno 13 错误?
- c++ - 为什么我在 split 函数中的这段代码中出现分段错误?
- node.js - ExpressValidator 不是函数
- databricks - Delta Lake 将多个文件压缩为单个文件
- python - 使用Python反转句子中的单词?
- javascript - 我正在尝试使用 React.js 联系表单实现 Netlify 表单
- reactjs - React + TypeScript 使用动态键名设置状态