首页 > 解决方案 > 如何在 laravel 中进行 JOINTURE(join)

问题描述

我有两个表 SALARIES 和 POINTAGES 并且它们之间有一个关系 hasMany belongsTo,我想为每个 POINTAGE 显示一个 SALARIES 对应,但它给了我空的数据表。 顾问.blade.php

@foreach($pointages as $pointage)
<tr>
  <td>{{ $pointage->datep }}</td>
  <td>{{ $pointage->chantier }}</td>
  <td>{{ $pointage->ouvrage }}</td>
  <td>{{ $pointage->nbrj }}</td>
  <td>{{ $pointage->solde }}</td>
  <td>{{ $pointage->salarie->nom }}</td>
</tr>
@endforeach

Pointage.php

 protected $fillable = [
  'salarie_id', 'datep', 'solde', 'nbrj' , 'ouvrage' , 'chantier' , 'prime' ,
];
 public function salarie(){
   return $this->belongsTo('App\Salarie');
 }

薪水.php

public function pointages(){
  return $this->hasMany('App\Pointage');
}

积分迁移:

public function up(){
  Schema::table('pointages', function (Blueprint $table) {
    $table->integer('salarie_id')->unsigned()->after('id');
    $table->foreign('salarie_id')->references('id')->on('salaries');  
  });
}

薪水控制器.php

 public function consulter()
     {
      $salaries = Salarie::with('pointages')->get();
      $pointages = Pointage::with(["salaries"])->has("salarie")->get();
      return view('salarie.consulter', compact('salaries','pointages'));
    }

标签: phplaravel

解决方案


您需要明确定义关系函数:

// app\Salarie.php
class Salarie extends Model
{
    protected $fillable = ['nome'];
    public function pointages(){
        return $this->hasMany('App\Pointage','salarie_id','id');
    }
}
// app\Pointage.php
class Pointage extends Model
{
    protected $fillable = [
        'salarie_id', 'datep', 'solde', 'nbrj' , 'ouvrage' , 'chantier' , 'prime' ,
      ];
    public function salarie(){
        return $this->belongsTo('App\Salarie');
    }
}

并使用如下方式来咨询与薪水表相关的所有积分:

// app\Http\Controllers\SalarieController.php
class SalarieController extends Controller
{
    public function consulter()
     {
        // test your model with this simple query
        // $salaries = Salarie::find(1);
        // $pointages = $salaries->pointages()->get();
        // return view('salarie.consulter', compact('pointages'));

        // if the upon test runs well, the follow codes will work 
        $salaries_ids = Salarie::with('pointages')->pluck('id');
        $pointages  = Pointage::whereHas('salarie', function($query) use ($salaries_ids) {
            $query->whereIn('salarie_id', $salaries_ids);
        })->get();
        return view('salarie.consulter', compact('pointages'));
    }
}

希望对你有帮助,有需要可以问我!


推荐阅读