laravelÈýÕűíÒ»¶Ô¶àÔõô²é
ÔÚlaravelÖУ¬ÎÒÃǾ³£ÐèҪʹÓùØϵÐÍÊý¾Ý¿âÀ´´æ´¢ºÍÖÎÀíÊý¾Ý£¬¶øÒ»¶Ô¶à¹ØϵÊÇÆäÖÐ×î³£¼ûµÄÒ»ÖÖ¡£Ò»¶Ô¶à¹ØϵָµÄÊÇÒ»¸öÄ£×ÓÓµÓжà¸ö¹ØÁªÄ£×ӵĹØϵ£¬Í¨³£ÓÃÓÚʵÏÖһЩ³£¼ûµÄÓªÒµ³¡¾°£¬ºÃ±ÈÒ»¸öÓû§¶ÔÓ¦¶à¸ö¶©µ¥»òÕßÒ»¸ö¿Î³Ì¶ÔÓ¦¶à¸öѧÉúµÈ¡£
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃEloquent ORMÀ´ÊµÏÖÒ»¶Ô¶à¹ØϵÅÌÎÊ¡£ÏÂÃæÎÒ½«ÏêϸÏÈÈÝÔõÑùʹÓÃLaravelÖеÄEloquentÄ£×ÓÅÌÎÊÈýÕűíÒ»¶Ô¶à¹Øϵ¡£
Éè¼ÆÈýÕűí
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÉè¼ÆÈýÕÅ±í£¬»®·ÖÊÇÖ÷±í¡¢×Ó±íºÍ×Ó±íÍâ¼ü¹ØÁª±í¡£ÒÔÏÂÊÇʾÀý±íµÄÉè¼Æ£º
Ö÷±í£ºusers
id | name | |
---|---|---|
1 | Tom | tom@laravel.com |
2 | Jerry | jerry@laravel.com |
3 | Bob | bob@laravel.com |
×Ó±í£ºorders
id | order_no | user_id |
---|---|---|
1 | 1001 | 1 |
2 | 1002 | 2 |
3 | 1003 | 3 |
4 | 1004 | 1 |
×Ó±íÍâ¼ü¹ØÁª±í£ºorder_items
id | order_id | product_name |
---|---|---|
1 | 1 | apple |
2 | 1 | banana |
3 | 2 | pear |
4 | 4 | orange |
5 | 4 | grape |
½¨ÉèLaravelÄ£×Ó
ÔÚLaravelÖУ¬ÎÒÃÇÐèÒª½¨ÉèÈý¸öÄ£×Ó£¬»®·Ö¶ÔÓ¦ÈýÕÅ±í¡£ÔÚ½¨ÉèÄ£×ÓµÄʱ¼ä£¬ÎÒÃÇÐèÒª½ç˵ģ×ÓÖ®¼äµÄ¹ØÁª¹Øϵ¡£
Ö÷±íÄ£×Ó£ºUser
class User extends Model { public function orders() { return $this->hasMany(Order::class); } }
µÇ¼ºó¸´ÖÆ
×Ó±íÄ£×Ó£ºOrder
class Order extends Model { public function user() { return $this->belongsTo(User::class); } public function items() { return $this->hasMany(OrderItem::class); } }
µÇ¼ºó¸´ÖÆ
×Ó±íÍâ¼ü¹ØÁª±íÄ£×Ó£ºOrderItem
class OrderItem extends Model { public function order() { return $this->belongsTo(Order::class); } }
µÇ¼ºó¸´ÖÆ
ÅÌÎÊÒ»¶Ô¶à¹Øϵ
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃEloquent ORMÀ´ÊµÏÖÒ»¶Ô¶à¹ØϵÅÌÎÊ¡£ÒÔÏÂÊÇÅÌÎÊһλÓû§µÄËùÓж©µ¥¼°ÆäϵÄËùÓж©µ¥ÏîµÄ´úÂëʾÀý£º
$user = User::find(1); foreach ($user->orders as $order) { echo $order->order_no; foreach ($order->items as $item) { echo $item->product_name; } }
µÇ¼ºó¸´ÖÆ
ÒÔÉÏ´úÂë»áÊä³öÓû§TomµÄËùÓж©µ¥¼°ÆäϵÄËùÓж©µ¥Ïî¡£
ÎÒÃÇÒ²¿ÉÒÔÖ±½ÓʹÓÃEloquentµÄ¹ØÁªÔ¤ÔØÈëÒªÁìÀ´ÅÌÎÊһλÓû§¼°Æ䶩µ¥¼°ÆäÏÂËùÓж©µ¥Ï
$user = User::with('orders.items')->find(1); foreach ($user->orders as $order) { echo $order->order_no; foreach ($order->items as $item) { echo $item->product_name; } }
µÇ¼ºó¸´ÖÆ
ÒÔÉÏ´úÂë»áÊä³öÓû§TomµÄËùÓж©µ¥¼°ÆäϵÄËùÓж©µ¥ÏÓëÉÏÃæµÄ·½·¨Ïà±È£¬¸Ã·½·¨ÓиüºÃµÄÐÔÄÜÌåÏÖ¡£
×ܽá
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃEloquent ORMºÜÊÇÀû±ãµØʵÏÖÒ»¶Ô¶à¹ØϵÅÌÎÊ¡£Ö»ÐèÔÚÄ£×ÓÖнç˵ºÃ¹ØÁª¹Øϵ£¬¾Í¿ÉÒÔÇáËɵػñÈ¡µ½Ö¸¶¨Ä£×ÓµÄËùÓйØÁªÊý¾Ý¡£Í¬Ê±£¬ÎÒÃÇÒ²¿ÉÒÔʹÓùØÁªÔ¤ÔØÈëÒªÁìÀ´ÓÅ»¯ÅÌÎÊÐÔÄÜ£¬ÈÃÎÒÃǵÄÓ¦ÓÃÔ½·¢¸ßЧÎȹ̡£
ÒÔÉϾÍÊÇlaravelÈýÕűíÒ»¶Ô¶àÔõô²éµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡