Laravel: How to get related table columns with active load

I have three database tables.

CREATE TABLE `tblproject` (
  `ProjectID` int(11) NOT NULL,
  `ProjectStatusID` varchar(30) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

CREATE TABLE `tblSkills` (
  `SkillID` int(11) NOT NULL,
  `Skill` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

CREATE TABLE `tblprojectSkills` (
  `ProjectSkillID` int(11) NOT NULL,
  `ProjectID` int NOT NULL,
  `SkillID` int NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

In the above tables. SkillIDconnected in tblSkillsand tblprojectSkills. ProjectIDapplies to Projectand projectSkillstable

My project model is below.

class Project_Model extends Model
{
    protected $table = "tblproject";
    protected $primaryKey = "ProjectID";
    public $timestamps = false;

    public function ProjectSkills() {
        return $this->hasMany('\App\Models\ProjectSkill_Model', 'ProjectID');
    }        
}

Database query in laravel 5.1 below.

\App\Models\Project\Project_Model
::with('ProjectSkills')
->where('ProjectID', '=', $ProjectID)->first();

Question

I can get the skill ID, but how can I get the name of the skill from the skills table?

+4
source share
1 answer

You can select the required fields with closing:

\App\Models\Project\Project_Model
::with('ProjectSkills' => function($q)
{
    $q->select('SkillID', 'Skill');
})
->where('ProjectID', '=', $ProjectID)->first();

Alternatively, you can add the required fields directly in relation to your model:

public function ProjectSkills() {
    return $this->hasMany('\App\Models\ProjectSkill_Model', 'ProjectID')
                ->select('SkillID', 'Skill');
} 
+1
source

Source: https://habr.com/ru/post/1621014/


All Articles