laravelÅÌÎÊ×÷·ÏÒ»¶Ô¶à
laravelÊÇÄ¿½ñ½ÏΪʢÐеĿªÔ´php webÓ¦Óÿò¼ÜÖ®Ò»£¬ÓÉÓÚÆäÒ×ÓᢸßЧºÍÎÞаÐÔ£¬Ô½À´Ô½¶àµÄ¿ª·¢ÕßʹÓÃlaravelÀ´½¨Éè¸ßÖÊÁ¿webÓ¦Óá£
ÔÚLaravelÖУ¬ÎÒÃǾ³£»áÓöµ½Ò»¶Ô¶àµÄÊý¾Ý¹Øϵ£¬Ò²¾ÍÊÇÒ»¸öÖ÷±íºÍ¶à¸ö´Ó±íÖ®¼äµÄ¹Øϵ¡£ÕâÖÖ¹ØϵÔÚÊý¾Ý¿âÖпÉÒÔͨ¹ýÍâ¼üÀ´ÊµÏÖ¡£ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃEloquent ORM£¨Object-Relational Mapping£©À´Àû±ãµØ¾ÙÐÐÒ»¶Ô´ó¶¼¾ÝµÄÅÌÎʲÙ×÷¡£±¾ÎÄÖ÷ÒªÏÈÈÝÔõÑùÔÚLaravelÖÐÅÌÎʺÍ×÷·ÏÒ»¶Ô¶àµÄÊý¾Ý¹Øϵ¡£
Ò»¡¢ÅÌÎÊÒ»¶Ô¶àµÄÊý¾Ý¹Øϵ
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃEloquent ORMÀ´ÅÌÎÊÒ»¶Ô¶àµÄÊý¾Ý¹Øϵ¡£Ê×ÏÈÎÒÃÇÐèÒª½ç˵ºÃÏìÓ¦µÄÄ£×Ӻ͹Øϵ£¬ÀýÈçÎÒÃÇÓÐÒ»¸ö¡°users¡±±íºÍÒ»¸ö¡°orders¡±±í£¬Ã¿¸öÓû§¿ÉÒÔÓжà¸ö¶©µ¥£¬ÎÒÃÇ¿ÉÒÔÔÚÓû§Ä£×ÓÖнç˵һ¸öorders()ÒªÁìÀ´ÌåÏÖÕâ¸öÒ»¶Ô¶àµÄ¹Øϵ£º
class User extends Model { /** * »ñÈ¡ÓëÓû§Ïà¹ØÁªµÄËùÓж©µ¥¡£ */ public function orders() { return $this->hasMany('AppOrder'); } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇʹÓÃhasMany()ÒªÁìÀ´½ç˵ÓëÓû§Ïà¹ØÁªµÄËùÓж©µ¥£¬¸ÃÒªÁìÎüÊÕÁ½¸ö²ÎÊý£¬µÚÒ»¸ö²ÎÊýÊÇÁ¥ÊôÄ£×ÓµÄÃû³Æ£¬µÚ¶þ¸ö²ÎÊýÊÇÍâ¼üµÄÃû³Æ£¨Ä¬ÈÏÇéÐÎÏ£¬Íâ¼üÃû³ÆÊÇÁ¥ÊôÄ£×ÓµÄÃû³Æ¼ÓÉÏ_id£©¡£½ÓÏÂÀ´£¬ÎÒÃǾͿÉÒÔÏñÏÂÃæÕâÑùʹÓÃorders()ÒªÁìÀ´ÅÌÎÊÓëÓû§Ïà¹ØÁªµÄËùÓж©µ¥£º
$user = User::find(1); // »ñÈ¡ÓëÓû§Ïà¹ØÁªµÄËùÓж©µ¥ $orders = $user->orders;
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇÊ×ÏÈʹÓÃfind()ÒªÁìÀ´²éÕÒIDΪ1µÄÓû§¹¤¾ß£¬È»ºóʹÓÃ$user->ordersÀ´»ñÈ¡Óë¸ÃÓû§Ïà¹ØÁªµÄËùÓж©µ¥¡£
ÈôÊÇÎÒÃÇÐèÒª½øÒ»²½É¸Ñ¡¶©µ¥£¬¿ÉÒÔʹÓÃÅÌÎʽṹÆ÷À´¶ÔÅÌÎʾÙÐйýÂË£¬ÀýÈ磺
// »ñÈ¡ÓëÓû§Ïà¹ØÁªµÄ¼ÛÇ®Áè¼Ý10ÔªµÄ¶©µ¥ $orders = $user->orders()->where('price', '>', 10)->get();
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇʹÓÃwhere()ÒªÁìÀ´É¸Ñ¡¶©µ¥µÄ¼ÛÇ®Áè¼Ý10ÔªµÄ¶©µ¥¡£
¶þ¡¢×÷·ÏÒ»¶Ô¶àµÄÊý¾Ý¹Øϵ
ÓÐʱ¼ä£¬ÔÚLaravelÖУ¬ÎÒÃÇÐèÒª×÷·ÏÒ»¸öÖ÷±íºÍÒ»¸ö´Ó±íÖ®¼äµÄÒ»¶Ô¶à¹Øϵ¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔ½«Ä³¸ö¶©µ¥Á¥ÊôÓÚij¸öÓû§ÉÏ£¬Ê¹Ö®³ÉΪδ¹ØÁª×´Ì¬¡£
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔͨ¹ý½«Íâ¼üÉèÖÃΪnullÀ´×÷·ÏÒ»Ìõ¼Í¼ºÍÆäÁ¥ÊôÄ£×ÓÖ®¼äµÄ¹Øϵ¡£ÀýÈ磬ÈôÊÇÎÒÃÇÒª½«IDΪ1µÄ¶©µ¥Á¥ÊôÓÚIDΪ2µÄÓû§ÉÏ£¬¿ÉÒÔÏñÏÂÃæÕâÑù²Ù×÷£º
$order = Order::find(1); // ×÷·Ï¸Ã¶©µ¥ÓëÖ®¹ØÁªµÄÓû§ $order->user_id = null; $order->save();
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇÊ×ÏÈʹÓÃfind()ÒªÁìÀ´²éÕÒIDΪ1µÄ¶©µ¥¹¤¾ß£¬È»ºó½«¸Ã¶©µ¥µÄuser_idÊôÐÔÉèÖÃΪnull£¬×îºóʹÓÃsave()ÒªÁìÀ´ÉúÑĸü¸Ä¡£
ÈôÊÇÎÒÃÇÐèÒª×÷·ÏÒ»¸öÓû§ºÍÆäÏà¹ØÁªµÄËùÓж©µ¥Ö®¼äµÄ¹Øϵ£¬¿ÉÒÔÏñÏÂÃæÕâÑù²Ù×÷£º
$user = User::find(1); // ×÷·Ï¸ÃÓû§ÓëÏà¹ØÁª¶©µ¥Ö®¼äµÄ¹Øϵ $user->orders()->update(['user_id' => null]);
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇÊ×ÏÈʹÓÃfind()ÒªÁìÀ´²éÕÒIDΪ1µÄÓû§¹¤¾ß£¬È»ºóʹÓÃorders()ÒªÁìÀ´»ñÈ¡¸ÃÓû§Ïà¹ØÁªµÄËùÓж©µ¥£¬½Ó×ÅʹÓÃupdate()ÒªÁìÀ´½«ËùÓж©µ¥µÄuser_idÊôÐÔÉèÖÃΪnull¡£
Èý¡¢×ܽá
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃEloquent ORMÀ´Àû±ãµØ¾ÙÐÐÒ»¶Ô´ó¶¼¾ÝµÄÅÌÎʲÙ×÷¡£Í¨³£ÎÒÃÇ¿ÉÒÔͨ¹ý½ç˵ÏìÓ¦µÄÄ£×Ӻ͹ØϵÀ´ÊµÏÖÒ»¶Ô¶àµÄÊý¾Ý¹Øϵ£¬ÔÚÅÌÎÊʱ¿ÉÒÔʹÓÃÅÌÎʽṹÆ÷À´½øÒ»²½É¸Ñ¡Êý¾Ý¡£Í¬Ê±£¬ÎÒÃÇÒ²¿ÉÒÔ×÷·ÏÒ»¸öÖ÷±íºÍ´Ó±íÖ®¼äµÄÒ»¶Ô¶à¹Øϵ£¬Í¨³£ÊÇͨ¹ý½«Íâ¼üÉèÖÃΪnullÀ´ÊµÏÖ¡£ÔÚ±àдLaravelÓ¦ÓóÌÐòʱ£¬ÎÒÃÇÓ¦¸Ã³ä·ÖʹÓÃEloquent ORMµÄ¹¦Ð§£¬ÒÔÌá¸ßÎÒÃǵĿª·¢Ð§Âʺͱàд´úÂëµÄÖÊÁ¿¡£
ÒÔÉϾÍÊÇlaravelÅÌÎÊ×÷·ÏÒ»¶Ô¶àµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡