Php 拉维尔雄辩的ORM关系
我有一个问题与雄辩的ORM关系我有公司模式和国家模式,一对多的关系,我使用了以下代码 公司模式Php 拉维尔雄辩的ORM关系,php,laravel,laravel-5,orm,Php,Laravel,Laravel 5,Orm,我有一个问题与雄辩的ORM关系我有公司模式和国家模式,一对多的关系,我使用了以下代码 公司模式 class Company_model extends Model { public $table = "company"; public $primaryKey = "id"; public function countries(){ return $this->belongsTo('App\Models
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";
}
国家/地区模式
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 ) )
试试这个
$result = $companyObj::with('countries')->get()->toArray();
您可以执行以下操作:
$result = Company_model::leftjoin('countries', 'countries.id', '=', 'company.countryId')->select('company.*', 'countries.countryName')->get();
我希望这会有帮助。通过laravel“with”查询是不可能的。您必须通过连接查询获得它,如:
Company_model::join('countries','countries.countryId','=','company.country')->select('company.*','countries.countryName')->get();
您必须在
Company\u 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']);
}
为什么你会有相同的答案?是的,我试过了,但没用。但是我认为使用ORM关系在性能上更快,这就是为什么我想尝试使用ORM关系是的,我在它正常工作之前就尝试过了。但是我认为使用ORM关系在性能上更快,这就是为什么我想尝试使用ORM关系在ORM关系中,当你得到代码时。。。。。。公司模型::带有('countries')->get()。。。。。。。。。它会自动将名为“countries”的关系数组添加到模型对象中,因为一家公司有多个国家。因此,如果您只想将国家/地区数组中的国家/地区名称添加到主数组中,则可以加入表并选择要在主数组中显示的特定列。