laravelÔõôÑéÖ¤ÊÇ·ñΨһ
ÔÚlaravel¿ò¼ÜÖУ¬ÑéÖ¤ÊäÈëÊý¾ÝµÄΨһÐÔÊÇÒ»¸ö³£¼ûÐèÇ󡣺ñÈÑéÖ¤Óû§µÄÓÊÏä»òÕßÊÖ»úºÅ£¬È·±£²»»á±»Öظ´×¢²á¡£
LaravelÌṩÁ˺ÜÊÇÀû±ãµÄÑéÖ¤¹æÔò¡ª¡ªunique¡£ÔÚ±íµ¥Ìύʱ£¬Ö»ÐèÒªÔÚ¹æÔòÖÐÌí¼Óunique:table,column¼´¿É£¬ÀýÈ磺
'username' => 'required|unique:users,username|max:255', 'email' => 'required|unique:users,email|max:255|email',
µÇ¼ºó¸´ÖÆ
ÒÔÉÏ´úÂëÖУ¬unique¹æÔòÖ¸Ã÷ÎúΨһÐÔÑéÖ¤±íusersºÍ×Ö¶Îusername»òemail£¬Õ⽫°ü¹ÜûÓÐÆäËûÓû§Ê¹ÓÃÏàͬµÄÓû§Ãû»òÓÊÏä¡£
¿ÉÊÇ£¬ÔÚÏÖʵӦÓÃÖУ¬unique¹æÔò²¢²»¿ÉÍêÈ«Öª×ã×ðÁú¿Ê±ÐèÇ󡣺ñȣ¬µ±ÎÒÃǸüÐÂÒ»ÌõÊý¾Ýʱ£¬ÔÓеÄΨһÐÔÑéÖ¤¹æÔò¿ÉÄܻᱨ´í¡ª¡ªÓÉÓÚÊý¾Ý¿âÖÐÒѾ±£´æÁËÎÒÃÇÕýÔÚ¸üеÄij¸öÖµ¡£
ΪÏàʶ¾öÕâ¸öÎÊÌ⣬LaravelÌṩÁËÒ»¸öÌØÁíÍâ²ÎÊý£ºexclude¡£ÀýÈ磺
'username' => 'required|unique:users,username,' . $userId . ',id|max:255',
µÇ¼ºó¸´ÖÆ
ÔÚÒÔÉÏ´úÂëÖУ¬$userId´ú±íÁËÄ¿½ñÒª¸üеÄÓû§ID£¬ÎÒÃÇͨ¹ýÔÚunique¹æÔòÖÐʹÓÃexclude²ÎÊý£¬¸æËßLaravelÔÚÑé֤ΨһÐÔʱ£¬É¨³ýÄ¿½ñÓû§¡£
³ýÁËexclude²ÎÊýÒÔÍ⣬Laravel»¹ÌṩÁËother_columns²ÎÊý£¬ÓÃÓÚÖ¸Ã÷ÆäËûÁеÄÌõ¼þ¡£ÀýÈ磺
'username' => Rule::unique('users') ->where(function ($query) use ($other_column_value) { return $query->where('other_column', $other_column_value); }) ->ignore($userId),
µÇ¼ºó¸´ÖÆ
ÒÔÉÏ´úÂëÖУ¬ÎÒÃÇʹÓÃÁËRuleÀàºÍwhereÒªÁì½ç˵ÁËÆäËûÁеÄÌõ¼þ£¬È·±£Î¨Ò»ÐÔÑéÖ¤Ö»»áÊܵ½Ö¸¶¨Ìõ¼þµÄÏÞÖÆ¡£ignore·½¹æÔòͬÑùÓÃÓÚɨ³ýÄ¿½ñÓû§¡£
×ܽáһϣ¬ÔÚLaravelÖÐÑé֤ΨһÐÔÐèҪעÖØÒÔÏÂÎÊÌ⣺
ÔÚunique¹æÔòÖÐʹÓÃexclude²ÎÊý£¬É¨³ýÄ¿½ñÊý¾ÝµÄÓ°Ïì¡£
¿ÉÒÔʹÓÃRuleÀàºÍwhereÒªÁì½ç˵ÆäËûÁеÄÌõ¼þ£¬È·±£Î¨Ò»ÐÔÑéÖ¤²»Êܵ½ÆäËûÁеÄÓ°Ïì¡£
ʹÓÃÒÔÉϼ¼ÇÉ£¬ÎÒÃÇ¿ÉÒÔÔ½·¢ÎÞаµØÑéÖ¤Êý¾ÝµÄΨһÐÔ£¬È·±£Êý¾ÝµÄÍêÕûÐÔºÍ׼ȷÐÔ¡£
ÒÔÉϾÍÊÇlaravelÔõôÑéÖ¤ÊÇ·ñΨһµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡