首页 > 解决方案 > 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  ) ) 

标签: phplaravellaravel-5orm

解决方案


您必须添加一个新方法,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']);
}

推荐阅读