×ðÁú¿­Ê±¹ÙÍøµÇ¼

laravelÈýÕűíÒ»¶Ô¶àÔõô²é

ÔÚlaravelÖУ¬ÎÒÃǾ­³£ÐèҪʹÓùØϵÐÍÊý¾Ý¿âÀ´´æ´¢ºÍÖÎÀíÊý¾Ý£¬¶øÒ»¶Ô¶à¹ØϵÊÇÆäÖÐ×î³£¼ûµÄÒ»ÖÖ¡£Ò»¶Ô¶à¹ØϵָµÄÊÇÒ»¸öÄ£×ÓÓµÓжà¸ö¹ØÁªÄ£×ӵĹØϵ£¬Í¨³£ÓÃÓÚʵÏÖһЩ³£¼ûµÄÓªÒµ³¡¾°£¬ºÃ±ÈÒ»¸öÓû§¶ÔÓ¦¶à¸ö¶©µ¥»òÕßÒ»¸ö¿Î³Ì¶ÔÓ¦¶à¸öѧÉúµÈ¡£

ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃEloquent ORMÀ´ÊµÏÖÒ»¶Ô¶à¹ØϵÅÌÎÊ¡£ÏÂÃæÎÒ½«ÏêϸÏÈÈÝÔõÑùʹÓÃLaravelÖеÄEloquentÄ£×ÓÅÌÎÊÈýÕűíÒ»¶Ô¶à¹Øϵ¡£

Éè¼ÆÈýÕűí

Ê×ÏÈ£¬ÎÒÃÇÐèÒªÉè¼ÆÈýÕűí£¬»®·ÖÊÇÖ÷±í¡¢×Ó±íºÍ×Ó±íÍâ¼ü¹ØÁª±í¡£ÒÔÏÂÊÇʾÀý±íµÄÉè¼Æ£º

Ö÷±í£ºusers

id name email
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ÈýÕűíÒ»¶Ô¶àÔõô²éµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡

ÃâÔð˵Ã÷£ºÒÔÉÏչʾÄÚÈÝȪԴÓÚÏàÖúýÌå¡¢ÆóÒµ»ú¹¹¡¢ÍøÓÑÌṩ»òÍøÂçÍøÂçÕûÀí£¬°æȨÕùÒéÓë±¾Õ¾Î޹أ¬ÎÄÕÂÉæ¼°¿´·¨Óë¿´·¨²»´ú±í×ðÁú¿­Ê±¹ÙÍøµÇ¼ÂËÓÍ»úÍø¹Ù·½Ì¬¶È£¬Çë¶ÁÕß½ö×ö²Î¿¼¡£±¾ÎĽӴýתÔØ£¬×ªÔØÇë˵Ã÷À´ÓÉ¡£ÈôÄúÒÔΪ±¾ÎÄÇÖÕ¼ÁËÄúµÄ°æȨÐÅÏ¢£¬»òÄú·¢Ã÷¸ÃÄÚÈÝÓÐÈκÎÉæ¼°ÓÐÎ¥¹«µÂ¡¢Ã°·¸Ö´·¨µÈÎ¥·¨ÐÅÏ¢£¬ÇëÄúÁ¬Ã¦ÁªÏµ×ðÁú¿­Ê±¹ÙÍøµÇ¼ʵʱÐÞÕý»òɾ³ý¡£

Ïà¹ØÐÂÎÅ

ÁªÏµ×ðÁú¿­Ê±¹ÙÍøµÇ¼

18523999891

¿É΢ÐÅÔÚÏß×Éѯ

ÊÂÇéʱ¼ä£ºÖÜÒ»ÖÁÖÜÎ壬9:30-18:30£¬½ÚãåÈÕÐÝÏ¢

QR code
ÍøÕ¾µØͼ