laravel È¥µôpovit
laravel ÊÇÒ»¿îÊ¢ÐÐµÄ php web ¿ò¼Ü£¬ÌṩÁËһЩºÜÊÇÀû±ãµÄ¹¦Ð§ºÍ¹¤¾ß£¬Ê¹µÃ web ¿ª·¢±äµÃÔ½·¢¼òÆӺͿìËÙ¡£ÆäÖУ¬pivot ÊÇÒ»¸öºÜÊÇÖ÷ÒªµÄ¹¦Ð§£¬ÓÃÓÚ´¦Àí¶à¶Ô¶à¹Øϵ¡£¿ÉÊÇ£¬ÔÚijЩÇéÐÎÏ£¬ÎÒÃÇ¿ÉÄÜÐèҪȥµô pivot¡£
ΪʲôҪȥµô Pivot£¿
ÔÚ¿ª·¢Àú³ÌÖУ¬ÓÐʱ¼ä·ºÆðÁË Pivot µÄÏÞÖÆ£¬ÎÒÃÇ¿ÉÄÜÐèÒª¶Ô¶à¶Ô¶à¹Øϵ¾ÙÐиü¶àµÄ¶¨ÖƺͿØÖÆ¡£´Ëʱ£¬È¥µô Pivot ¿ÉÒÔÌṩ¸ü´óµÄÎÞаÐÔ¡£ÏÂÃæÊÇһЩ³£¼ûµÄÇéÐΣº
¶¨ÖƹØϵ±íµÄ×Ö¶ÎÃû³Æ
Pivot »á×Ô¶¯ÌìÉúÒ»ÆäÖÐÐÄ±í£¬ÆäÖаüÀ¨Á½¸öÍâ¼üºÍÒ»¸öʱ¼ä´Á¡£ÔÚijЩÇéÐÎÏ£¬ÎÒÃÇ¿ÉÄÜÐèÒª¶¨ÖƸü¶àµÄ×ֶΣ¬ºÃ±ÈÌí¼ÓÒ»¸ö״̬×ֶΡ£Õâʱ¼ä£¬È¥µô Pivot£¬ÎÒÃÇ¿ÉÒÔÊÖ¶¯½¨ÉèÒ»ÆäÖÐÐÄ±í£¬¶¨ÖÆ×Ö¶ÎÃû³ÆºÍÀàÐÍ¡£
¿ØÖƹØϵ±íµÄ½¨ÉèºÍ¸üÐÂ
µ±ÎÒÃÇʹÓà Laravel µÄ Pivot ¹¦Ð§Ê±£¬ÈôÊǹØϵ±í²»±£´æ£¬¿ò¼Ü»á×Ô¶¯½¨Éè¡£¿ÉÊÇ£¬ÔÚijЩÇéÐÎÏ£¬ÎÒÃÇ¿ÉÄÜÐèÒªÊÖ¶¯½¨ÉèÕâ¸ö±í£¬²¢ÔÚ¸üйØϵʱ¾ÙÐиü¶àµÄ¿ØÖÆ¡£È¥µô Pivot ºó£¬ÎÒÃÇ¿ÉÒÔÊÖ¶¯±àд SQL Óï¾ä£¬×ÔÓÉ¿ØÖƹØϵ±íµÄ½¨ÉèºÍ¸üС£
´¦ÀíÖØ´óµÄ¶à¶Ô¶à¹Øϵ
Laravel µÄ Pivot ¹¦Ð§Í¨³£ÊÊÓÃÓÚ¼òÆӵĶà¶Ô¶à¹Øϵ¡£¿ÉÊÇ£¬ÔÚһЩÖØ´óµÄÇéÐÎÏ£¬ÎÒÃÇ¿ÉÄÜÐèÒª¸ü¶àµÄ¶¨ÖƺͿØÖÆ¡£ºÃ±È£¬ÎÒÃÇÐèÒª´¦Àí¶àÖرí¸ñÖ®¼äµÄ¶à¶Ô¶à¹Øϵ£¬»òÕßÐèÒªÔÚ¹Øϵ±íÖÐÌí¼Ó¸ü¶àµÄ×ֶξÙÐд¦Àí¡£Õâʱ¼ä£¬È¥µô Pivot£¬ÎÒÃÇ¿ÉÒÔƾ֤ÐèÒª¾ÙÐиü¶àµÄ¹¹½¨ºÍ¿ØÖÆ¡£
ÔõÑùÈ¥µô Pivot£¿
È¥µô Pivot µÄÒªÁìÓжàÖÖ£¬ÏÂÃæÏÈÈÝÁ½ÖÖ³£¼ûµÄ·½·¨¡£
ÒªÁìÒ»£ºÊÖ¶¯½¨ÉèÖÐÐıí
Ê×ÏÈ£¬ÔÚÊý¾Ý¿âÖн¨ÉèÒ»ÆäÖÐÐÄ±í¡£
CREATE TABLE `user_role` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(11) unsigned NOT NULL, `role_id` int(11) unsigned NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
µÇ¼ºó¸´ÖÆ
ÔÚÄ£×ÓÖнç˵¶à¶Ô¶à¹Øϵ
class User extends Model { public function roles() { return $this->belongsToMany(Role::class, 'user_role', 'user_id', 'role_id'); } } class Role extends Model { public function users() { return $this->belongsToMany(User::class, 'user_role', 'role_id', 'user_id'); } }
µÇ¼ºó¸´ÖÆ
ÔÚ¿ØÖÆÆ÷ÖÐʹÓÃ
$user = User::find(1); $roles = $user->roles;
µÇ¼ºó¸´ÖÆ
ÒªÁì¶þ£ºÊ¹ÓÃÖÐÐļþ
½¨ÉèÒ»ÆäÖÐÐļþ
php artisan make:middleware SimplifyPivotMiddleware
µÇ¼ºó¸´ÖÆ
ÔÚÖÐÐļþÖд¦Àí¶à¶Ô¶à¹Øϵ
namespace AppHttpMiddleware; use Closure; class SimplifyPivotMiddleware { public function handle($request, Closure $next) { $user = $request->user; $roles = $user->roles()->withTimestamps()->select('id', 'name')->get(); $user->setRelation('roles', $roles); return $next($request); } }
µÇ¼ºó¸´ÖÆ
ÔÚ·ÓÉÖÐʹÓÃÖÐÐļþ
Route::get('/user/{id}/roles', function ($id) { $user = User::with('roles')->find($id); return response()->json(['status' => 1, 'data' => $user->roles]); })->middleware(SimplifyPivotMiddleware::class);
µÇ¼ºó¸´ÖÆ
½áÂÛ
Pivot ÊÇ Laravel ´¦Àí¶à¶Ô¶à¹ØϵµÄÒ»Öֺܺõķ½·¨¡£¿ÉÊÇ£¬ÔÚijЩÇéÐÎÏ£¬ÎÒÃÇ¿ÉÄÜÐèҪȥµô Pivot£¬²¢ÊÖ¶¯½¨ÉèÖÐÐÄ±í£¬»òʹÓÃÖÐÐļþÀ´´¦Àí¶à¶Ô¶à¹Øϵ¡£ÕâÑù¿ÉÒÔÌṩ¸ü´óµÄÎÞаÐԺͿØÖÆÄÜÁ¦£¬µ«ÐèÒªÖ§¸¶¸ü¶àµÄ±àÂëºÍά»¤±¾Ç®¡£
ÒÔÉϾÍÊÇlaravel È¥µôpovitµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡