Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在Laravel中为Pivot模型绑定用户路由模型_Php_Laravel 5_Eloquent_Pivot Table_Php 7.2 - Fatal编程技术网

Php 如何在Laravel中为Pivot模型绑定用户路由模型

Php 如何在Laravel中为Pivot模型绑定用户路由模型,php,laravel-5,eloquent,pivot-table,php-7.2,Php,Laravel 5,Eloquent,Pivot Table,Php 7.2,拉韦尔五世:5.7 PHPV7.2.10 路由路径是:admin/partments/{partments}/associations/{association}/association-users/{association\u-user} 获取URL:http://127.0.0.1:8000/admin/apartments/1/associations/1/association-用户 透视模型:AssociationUser 在App\Providers\RouteServiceProv

拉韦尔五世:5.7

PHPV7.2.10

路由路径是:
admin/partments/{partments}/associations/{association}/association-users/{association\u-user}

获取URL:
http://127.0.0.1:8000/admin/apartments/1/associations/1/association-用户

透视模型:
AssociationUser

App\Providers\RouteServiceProvider
中,我添加了

public function boot()
    {
        parent::boot();

        Route::bind('association-user', function ($value) {
            return App\pivotes\AssociationUser::where('association_id', request()->route()->parameter('association')->id)->where('user_id', auth()->id())->first() ?? abort(404);
        });
    }
路由创建

route('apartments.associations.association-users.show', ['apartment' => $associationUser->association->apartment, 'association' => $associationUser->association, 'association_user' => $associationUser ])

如果我没有弄错的话,association\u user pivot表应该有association\u id和user\u id,两者的组合是唯一的,所以在您的路由中已经有了
{association}
模型,所以我相信您可以使用

public function getRouteKeyName()
{
    return 'user_id';
}
在pivot模型类中,用户id将出现在您的url中,您将拥有关联和用户模型的组合

您不需要

 Route::bind('association-user', function ($value) {
            return App\pivotes\AssociationUser::where('association_id', request()->route()->parameter('association')->id)->where('user_id', auth()->id())->first() ?? abort(404);
        }); 

在您的
App\Providers\RouteServiceProvider

中,您总是得到404?如果我得到的是索引页而不是显示页,您可以看到我缺少那里的模型。我会将此逻辑移到中间件或控制器方法中,因为使用路由绑定,这件事是隐藏的,就像魔术一样,但它是坏的。@TheAllen为数据透视模型获取路由模型绑定的正确方法是什么?您只需将它绑定到正确的模型类,并在中间件或控制器中验证它们之间的关系。