Laravel¿ª·¢£ºÔõÑùʹÓÃLaravel EloquentʵÏÖ¹Øϵģ×Ó£¿
laravelÊÇÒ»¸öÊ¢ÐеÄphp webÓ¦ÓóÌÐò¿ò¼Ü£¬ËüµÄ¹ØϵÐÍÊý¾Ý¿âorm¹¤¾ßeloquentÌṩÁËÒ×ÓÚʹÓõġ¢ÓÅÑŵġ¢¿ìËÙµÄÊý¾Ý¿â»á¼û·½·¨£¬Ê¹¿ª·¢Ö°Ô±Äܹ»ÇáËɵØÖÎÀíÊý¾Ý¿â¹Øϵ¡£laravel eloquentÌṩÁËÒ»ÖÖºÜÊÇÀû±ãµÄÒªÁìÀ´½ç˵ģ×ÓÖ®¼äµÄ¹Øϵ¡£ÔÚ±¾ÎÄÖУ¬ÎÒÃǽ«ÉîÈë̽ÌÖÔõÑùʹÓÃlaravel eloquentʵÏÖ¹Øϵģ×Ó¡£
ʲôÊÇLaravel Eloquent
Laravel EloquentÊÇÒ»ÖÖºÜÊÇÇ¿Ê¢µÄORM (object-relational mapping)ÊÖÒÕ£¬¿ÉÓÃÓÚ½«¹¤¾ßÓ³Éäµ½¹ØϵÐÍÊý¾Ý¿âÖÐµÄ±í¡£EloquentÊÇLaravel¿ò¼ÜµÄÒ»²¿·Ö£¬ÌṩÁËÒ»ÕûÌײÙ×÷Êý¾Ý¿âµÄ¹¦Ð§¡£
ÔÚÕâÀÎÒÃǽ«Ê¹ÓÃEloquentÀ´ÊµÏÖÖÖÖÖ¹Øϵ£¬ÀýÈçÒ»¶ÔÒ»£¬Ò»¶Ô¶àºÍ¶à¶Ô¶à¹Øϵ¡£ÒÔÏÂÊÇÔõÑù½¨É輸¸öÓйØϵµÄÄ£×ÓµÄʾÀý£¬ÒÔ±ã¸üºÃµØÃ÷È·EloquentµÄÇ¿Ê¢Ö®´¦¡£
ʵÏÖÒ»¶ÔÒ»¹Øϵ
ÔÚLaravel¹¤¾ßÖУ¬Ê¹ÓÃbelongsToºÍhasOneº¯ÊýÀ´ÌåÏÖÒ»¶ÔÒ»¹Øϵ¡£ÈÃÎÒÃÇ¿´¿´ÔõÑùͨ¹ýEloquentʵÏÖÒ»¶ÔÒ»¹Øϵ¡£
ÐèÒª½¨ÉèÁ½¸öÄ£×Ó£¬ºÃ±ÈѧÉúºÍѧУģ×Ó¡£ÔÚѧÉúÄ£×ÓÖУ¬¿ÉÒÔͨ¹ýbelongsToº¯Êý½ç˵ѧУģ×Ó£¬ÈçÏÂËùʾ£º
class Student extends Model { public function school() { return $this->belongsTo(School::class); } }
µÇ¼ºó¸´ÖÆ
ÔÚѧУģ×ÓÖУ¬¿ÉÒÔͨ¹ýhasOneº¯Êý½ç˵ѧÉúÄ£×Ó£¬ÈçÏÂËùʾ£º
class School extends Model { public function student() { return $this->hasOne(Student::class); } }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÀý×ÓÖУ¬ÎÒÃǽç˵ÁËÁ½¸öÄ£×ÓÖ®¼äµÄ¹Øϵ£¬¼´Ñ§ÉúºÍѧУ¡£Ñ§ÉúÖ»ÊôÓÚÒ»¸öѧУ£¬¶øѧУֻÓÐÒ»¸öѧÉú¡£
ʵÏÖÒ»¶Ô¶à¹Øϵ
ÔÚLaravel EloquentÖУ¬Ê¹ÓÃbelongsToºÍhasManyº¯ÊýÀ´ÌåÏÖÒ»¶Ô¶à¹Øϵ¡£ÔÚÕâ¸öÀý×ÓÖУ¬ÈÃÎÒÃÇ¿´¿´ÔõÑùͨ¹ýEloquentʵÏÖÒ»¶Ô¶à¹Øϵ¡£
ÐèÒª½¨ÉèÁ½¸öÄ£×Ó£¬ºÃ±È²¿·ÖºÍÔ±¹¤Ä£×Ó¡£ÔÚÔ±¹¤Ä£×ÓÖУ¬¿ÉÒÔͨ¹ýbelongsToº¯Êý½ç˵²¿·ÖÄ£×Ó£¬ÈçÏÂËùʾ£º
class Employee extends Model { public function department() { return $this->belongsTo(Department::class); } }
µÇ¼ºó¸´ÖÆ
ÔÚ²¿·ÖÄ£×ÓÖУ¬¿ÉÒÔͨ¹ýhasManyº¯Êý½ç˵Ա¹¤Ä£×Ó£¬ÈçÏÂËùʾ£º
class Department extends Model { public function employees() { return $this->hasMany(Employee::class); } }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÀý×ÓÖУ¬ÎÒÃǽç˵ÁËÁ½¸öÄ£×ÓÖ®¼äµÄ¹Øϵ£¬¼´²¿·ÖºÍÔ±¹¤¡£²¿·Ö¿ÉÒÔÓжà¸öÔ±¹¤£¬¶øÒ»¸öÔ±¹¤Ö»ÊôÓÚÒ»¸ö²¿·Ö¡£
ʵÏÖ¶à¶Ô¶à¹Øϵ
ÔÚLaravel EloquentÖУ¬Ê¹ÓÃbelongsToManyº¯ÊýÀ´ÌåÏÖ¶à¶Ô¶à¹Øϵ¡£ÔÚÕâ¸öÀý×ÓÖУ¬ÈÃÎÒÃÇ¿´¿´ÔõÑùͨ¹ýEloquentʵÏÖ¶à¶Ô¶à¹Øϵ¡£
ÐèÒª½¨ÉèÁ½¸öÄ£×Ó£¬ºÃ±È¿Î³ÌºÍѧÉúÄ£×Ó¡£ÔÚѧÉúÄ£×ÓÖУ¬¿ÉÒÔͨ¹ýbelongsToManyº¯Êý½ç˵¿Î³ÌÄ£×Ó£¬ÈçÏÂËùʾ£º
class Student extends Model { public function courses() { return $this->belongsToMany(Course::class); } }
µÇ¼ºó¸´ÖÆ
ÔڿγÌÄ£×ÓÖУ¬¿ÉÒÔͨ¹ýbelongsToManyº¯Êý½ç˵ѧÉúÄ£×Ó£¬ÈçÏÂËùʾ£º
class Course extends Model { public function students() { return $this->belongsToMany(Student::class); } }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÀý×ÓÖУ¬ÎÒÃǽç˵ÁËÁ½¸öÄ£×ÓÖ®¼äµÄ¶à¶Ô¶à¹Øϵ£¬¼´¿Î³ÌºÍѧÉú¡£Ñ§Éú¿ÉÒÔÑ¡ÔñÐí¶à¿Î³Ì£¬¶ø¿Î³ÌÒ²¿ÉÒÔÓжà¸öѧÉú¡£
½áÂÛ
×ÜÖ®£¬Laravel EloquentÊÇÒ»¸öÇ¿Ê¢µÄORMÊÖÒÕ£¬Ê¹µÃÔÚLaravel¿ò¼ÜÖвÙ×÷¹ØϵÐÍÊý¾Ý¿â±äµÃÈÝÒס¢Àû±ã¡£±¾ÎÄÏÈÈÝÁËÔõÑùʹÓÃEloquentʵÏÖÒ»¶ÔÒ»¡¢Ò»¶Ô¶àºÍ¶à¶Ô¶à¹Øϵ£¬Äã¿ÉÒÔÔÚ¿ª·¢ÖÐʹÓÃÊʺÏÇéÐεĹØϵ¡£Ï£ÍûÕâƪÎÄÕÂÄÜ×ÊÖúÄú¸üºÃµØÃ÷È·Laravel EloquentµÄÇ¿Ê¢¹¦Ð§£¬ÒÔ¸üºÃµØÖÎÀíÓ¦ÓóÌÐòµÄÊý¾Ý¡£
ÒÔÉϾÍÊÇLaravel¿ª·¢£ºÔõÑùʹÓÃLaravel EloquentʵÏÖ¹Øϵģ×Ó£¿µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡