php - 如何在 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'));
}
解决方案
您需要明确定义关系函数:
// 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'));
}
}
希望对你有帮助,有需要可以问我!
推荐阅读
- amazon-web-services - AWSmobile-cli 是否已停产?
- cypress - 赛普拉斯:.each 循环查找具有价值的元素
- c# - 从 C# 到 C++ 封送数据类型的类型转换问题
- dart - Flutter:如何获取文本行数
- javascript - Axios,代理请求似乎不起作用
- ios - 突出显示按钮时如何获取事件而不是状态
- json - 在“加载”后访问 Json 数据
- python - 我想在 python gui 上更新 arduino 数据,但它没有发生,请有人找出问题
- hazelcast - hazelcast 领导人选举以两名领导人结束
- r - getOption("viewer") 发布的r版本是什么