【发布时间】:2021-08-15 13:13:51
【问题描述】:
我有两个具有多对多关系的表:
courriersstructurescourrier_structure
数据透视表包含:
idcourrier_idstructure_idvalide
valide 是一个布尔属性。
在第一种情况下,我通过表单插入了 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');
}
}
我的网络路线
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
我收到此错误的控制器:
未定义的属性: 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'));
}
【问题讨论】:
-
您可以将错误消息添加到您的问题中吗?
-
@shaedrich 是的,它完成了
-
要从关系中获取属性,不要使用括号:
$courrier->structure->id。它不是复数 (structures) 吗? -
@shaedrich 它是复数形式,是的,这只是一个错误现在我收到此错误:此集合实例上不存在属性 [id]。
-
因为它是
belongsToMany。您只需要收藏中的一件吗?
标签: php laravel controller pivot-table laravel-8