[英]Insert data in pivot table Controller Laravel 8
我有兩個具有多對多關系的表:
courriers
structures
courrier_structure
pivot 表包含:
id
courrier_id
structure_id
valide
valide
是 boolean 屬性。
在第一種情況下,我通過表單插入了courrier_id
和structure_id
。 接下來,當用戶單擊按鈕時,我希望將 1 放入驗證值中,並且我想通過valide
執行此操作。
我的模型如下所示:
class Courrier extends Model {
public function structures()
{
return $this->belongsToMany(Structure::class)->withTimestamps()
->withPivot('valide');
}
}
class Structure extends Model
{
use HasFactory;
protected $fillable = [
'nom_structure',
];
public function courriers(){
return $this->belongsToMany(Courrier::class)->withTimestamps()
->withPivot('valide');
}
}
我的 web 路線
Route::get('{id}/valider', [App\Http\Controllers\CourrierController::class, 'valider'])
->name('valider');
我對刀片的看法:
@foreach($courriers as $key => $courrier)
<td>
<a class='' onclick='return confirm("Êtes-vous sûr de vouloir valider la réception de ce courrier?")' href="{{ route('valider',$courrier->id) }}">
Valider
</a>
</td>
@endforeach
我的 controller 出現此錯誤:
未定義屬性:Illuminate\Database\Eloquent\Relations\BelongsToMany::$id
public function valider( Request $rquest, Courrier $courrier) {
$courrier->structures()->updateExistingPivot($courrier->structures()->id,
[$request->valide = 1]
);
return redirect()->route('nvCourriersDMO');
}
我正在研究結構id = 1的領域,
public function nvCourriersDMO(Request $request, Courrier $courrier)
{
$courriers = Courrier::join('courrier_structure', 'courriers.id',
'=', 'courrier_structure.courrier_id')-
>where('courrier_structure.structure_id','=','1')-
>where('courrier_structure.valide','=',NULL)->get();
return view("nvCourriersDMO", compact('courriers'));
}
Laravel 關系方法有時有點棘手。 如果您使用括號調用該方法(就像您在這里一樣),它會返回一個“關系類”實例。 在這種情況下, BelongsToMany
class 的實例。
如果將該方法作為屬性調用(不帶括號),則 Laravel 將返回關系目標。 在這種情況下, Structure
model 實例的集合。
這應該可以解決問題:
public function valider(Request $request, Courrier $courrier)
{
$pivotIds = $courrier->structures()->allRelatedIds();
$courrier->structures()->updateExistingPivot(
$pivotIds,
['valide' => 1]
);
return redirect()->route('nvCourriersDMO');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.