一对多和一对多的关系laravel

时间:2018-01-06 13:26:21

标签: php mysql laravel foreign-keys relationship

这是项目迁移

    Schema::create('projects', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('start_date');
        $table->string('end_date');
        $table->string('con');
        $table->timestamps();
    });

这是时间表迁移

    Schema::create('timesheets', function (Blueprint $table) {
        $table->increments('id');
        $table->string('user_id');
        $table->string('project_id');
        $table->string('day');
        $table->string('month');
        $table->string('year');
        $table->string('jalali');
        $table->string('timesheet_h');
        $table->string('timesheet_m');
        $table->timestamps();
    });

此用户迁移

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('mobile');
        $table->string('salary_base');
        $table->string('salary_base_h');
        $table->string('start_contract');
        $table->string('end_contract');
        $table->string('start_insurance');
        $table->string('end_insurance')->nullable();
        $table->string('first_salary');
        $table->string('date_birth');
        $table->string('melli_code');
        $table->string('s_number');
        $table->string('nda');
        $table->string('work_rules');
        $table->string('end_work')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

这是我的项目模型

public function timesheets()
{
    return $this->hasMany(timesheet::class,'project_id');
}

这是我的时间表模型:

public function projects()
{
    return $this->belongsTo(project::class,'project_id');
}

public function users()
{
    return $this->belongsTo(User::class,'user_id','id');
}

和我的用户模型

public function project_peoples()
{
    return $this->hasMany('App\project_people');
}
public function timesheets()
{
    return $this->belongsTo(timesheet::class);
}

public function projects()
{
    return $this->belongsTo(project::class);
}

现在我从项目中返回我的查询

public function allProject()
{
    $projects=project::with(['timesheets','users'])->get();

    return $projects;
  }

这是好的,但是timeheets.user_id中的user_id用户我无法将时间表拿出来并获得它

此控制器按时间表中的project_id返回项目和时间表,但时间表中的user_id返回时间表我不知道如何将其导入系统

2 个答案:

答案 0 :(得分:0)

使用dot syntax加载嵌套关系:

project::with('timesheets.users')->get();

答案 1 :(得分:0)

 public function upload($name,$id)
{
    $this->db->set('document',$name);
    $this->db->where('id',$id);
    $this->db->update('employee_details');
    return true;
} 

这是我的回报,我有2个用户,但重复我的2个用户:(