[英]Laravel Eloquent ORM Relationships
I have a issue with Eloquent ORM relationship i have company Model and Countries Model, One to Many relationship, I have used following codes. 我有一个雄辩的ORM关系问题,我有公司模型和国家模型,一对多关系,我使用了以下代码。
Company Model 公司模式
class Company_model extends Model
{
public $table = "company";
public $primaryKey = "id";
public function countries(){
return $this->belongsTo('App\Models\Countries','country','countryId');
}
}
Countries Model 国家模型
class Countries extends Model
{
public $table = "countries";
public $primaryKey = "countryId";
}
i have used the following code to retrieve the data i want to get company details along with countryName 我已使用以下代码检索要获取公司详细信息以及countryName的数据
$companyObj = new Company_model();
$result = $companyObj::with('countries')->get();
i get the results with company and countries details but the countries details come as an array i need it come without array also i need to take the country Name now all the details in the countries table comes to the array. 我得到了包含公司和国家/地区详细信息的结果,但是国家/地区详细信息以数组的形式出现,我需要它不包含数组,也需要使用国家/地区名称。现在,国家/地区表中的所有详细信息都进入了数组。
Now Result 现在结果
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] => ) ) )
I need the result like 我需要这样的结果
Array ( [0] => Array ( [id] => 1 [companyName] => Test [address] => [phone] => [email] => [website] => [companyImg] => 1 [create_by] => [create_time] => [countryName] => Test ) )
You've to add a new method in Company_model
that's have the method that only give the selected fields. 您必须在Company_model
中添加一个仅提供选定字段的方法。
class Company_model extends Model
{
public $table = "company";
public $primaryKey = "id";
public function countries(){
return $this->belongsTo('App\Models\Countries','country','countryId');
}
}
This is the new method. 这是新方法。
public function countriesIDs()
{
return $this->belongsTo('App\Models\Countries')->select(['name']);
}
尝试这个
$result = $companyObj::with('countries')->get()->toArray();
You can to do this: 您可以这样做:
$result = Company_model::leftjoin('countries', 'countries.id', '=', 'company.countryId')->select('company.*', 'countries.countryName')->get();
I hope it would helpful. 希望对您有所帮助。
It is not possible by laravel "with" query. 通过laravel“ with”查询是不可能的。 You have to get it by join query like: 您必须通过联接查询来获取它,例如:
Company_model::join('countries','countries.countryId','=','company.country')->select('company.*','countries.countryName')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.