我有两个表SALARIES和POINTAGES,并且它们之间的关系hasManyToToTo,我想为每个POINTAGE显示一个SALARIES对应关系,但这给了我空的数据表。 consulter.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');
}
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');
});
}
SalarieController.php
public function consulter()
{
$salaries = Salarie::with('pointages')->get();
$pointages = Pointage::with(["salaries"])->has("salarie")->get();
return view('salarie.consulter', compact('salaries','pointages'));
}
答案 0 :(得分:0)
您可以尝试一些操作:
with()
那样删除de Pointage::with("salaries")->has("salarie")->get();
中的括号在上面的示例中,Eloquent将尝试将Phone模型中的user_id与User模型中的id进行匹配。 Eloquent通过检查关系方法的名称并在方法名称后加上_id来确定默认的外键名称。但是,如果Phone模型上的外键不是user_id,则可以将自定义键名称作为第二个参数传递给belongsTo方法。
答案 1 :(得分:0)
您需要定义显式的关系函数:
// 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'));
}
}
希望这会有所帮助,问我是否需要!