In laravel we can create relation between the tables and can use them where ever we need it we need not to create custom queries or use query builder to retrieve data. I have written one of example of my worked project.
//hasOne relationship models
public function companyCountry() {
return $this->hasOne('App\Country', 'id', 'country_id');
}
public function companyState() {
return $this->hasOne('App\State', 'id', 'state_id');
}
public function compnayUserInfo() {
return $this->belongsTo('App\User', 'userid', 'userid');
}
// hasMany relationship models
public function companyDepartments() {
return $this->hasMany('App\CompanyDepartment', 'id', 'company_id');
}
public function getDetails_v2(){
$companyList = $this->where('userid', '=', Auth::user()->userid)->limit(1)->get();
$company = array();
$exist = $companyList->toArray(); if(empty($exist)){ return $company; }//Testing if the id exist or not
$company['Company'] = $companyList[0]->toArray();
$company['UserInfo'] = $companyList[0]->compnayUserInfo->toArray();
$company['Country'] = $companyList[0]->companyCountry->toArray();
$company['State'] = $companyList[0]->companyState->toArray();
return $company;
}
0 Comment(s)