我有一个问题与雄辩的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']);
}
试试这个
$result = $companyObj::with('countries')->get()->toArray();
您可以执行以下操作:
$result = Company_model::leftjoin('countries', 'countries.id', '=', 'company.countryId')->select('company.*', 'countries.countryName')->get();
我希望这会有帮助。