php – Laravel:如何在急切加载中获取关联表的列

我有三个数据库表.

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; 

在上表中. SkillID与tblSkills和tblprojectSkills相关.
ProjectID与Project和projectSkills表相关

我的项目模型如下.

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');
    }        
}

laravel 5.1中的数据库查询如下.

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

我可以获得技能ID,但是,我如何从技能表中获得技能名称?

最佳答案 您可以使用闭包选择所需的字段:

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

或者,您可以在模型的关系中直接添加所需的字段:

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