laravelÄܲ»¿É½ÓÁ½¸öÊý¾Ý¿â
laravelÊÇÒ»¸öÊ¢ÐеÄphp¿ò¼Ü£¬ÌṩÁËÐí¶àÇ¿Ê¢µÄÌØÕ÷ºÍ¹¤¾ß£¬Ê¹µÃ¿ª·¢webÓ¦ÓñäµÃÔ½·¢¸ßЧºÍ¼òÆÓ¡£ÔÚÏÖʵµÄÓ¦Óó¡¾°ÖУ¬ÎÒÃǾ³£ÐèÒªÅþÁ¬¶à¸öÊý¾Ý¿â£¬²¢ÔÚÕâЩÊý¾Ý¿âÖ®¼ä¾ÙÐÐÊý¾ÝµÄ½»»¥ºÍת´ï¡£Òò´Ë£¬ÕâƪÎÄÕ½«»áÌÖÂÛÔÚlaravelÖÐÔõÑù½ÓÈë¶à¸öÊý¾Ý¿â¡£
Ò»Ñùƽ³£À´Ëµ£¬LaravelĬÈÏÖ»ÅþÁ¬Ò»¸öÊý¾Ý¿â¡£ÕâÊÇÔÚconfig/database.phpÖеġ¯database¡¯×Ö¶ÎÖÐÉèÖõġ£±ðµÄ£¬ÎÒÃÇ»¹¿ÉÒÔΪÿ¸öÊý¾Ý¿âÉèÖÃÆäËüÉèÖÃÏÀýÈçÊý¾Ý¿âµÄÅþÁ¬Ãû³Æ£¬Ö÷»úÃû³Æ£¬Êý¾Ý¿âÃû³Æ£¬Óû§Ãû£¬ÃÜÂëµÈ¡£¿ÉÊÇ£¬ÈôÊÇÎÒÃÇÐèÒªÅþÁ¬¶à¸öÊý¾Ý¿â£¬ÎÒÃǸÃÔõÑù×öÄØ£¿
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃLaravelµÄEloquent ORMÒÔ¼°LaravelÌṩµÄDatabase Query BuilderÀ´ÅþÁ¬¶à¸öÊý¾Ý¿â¡£ÕâÁ½¸ö¹¤¾ß¶¼ÌṩÁËÐí¶à¸ßЧºÍÎÞаµÄÒªÁ죬ʹµÃ´ó¶¼¾Ý¿âµÄÅþÁ¬±äµÃ¼òÆÓ¶øÓÖÀû±ã¡£
ÉèÖÃÎļþÉèÖÃ
ͨ³£ÇéÐÎÏ£¬ÎÒÃÇ¿ÉÒÔͨ¹ýÐÞ¸ÄÉèÖÃÎļþÖеÄÊý¾Ý¿âÅþÁ¬À´ÅþÁ¬¶à¸öÊý¾Ý¿â¡£Ö»ÐèÒªÔÚconfig/database.phpÖÐÌí¼ÓÒ»¸öеÄÊý¾Ý¿âÅþÁ¬¼´¿É¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔÔöÌíÒ»¸öÃûΪ¡°mysql2¡±µÄÊý¾Ý¿âÅþÁ¬£º
‘default’ => env(‘DB_CONNECTION’, ‘mysql’),
‘connections’ => [
// Ö÷Êý¾Ý¿â
‘mysql’ => [
‘driver’ => ‘mysql’,
‘host’ => env(‘DB_HOST’, ‘127.0.0.1’),
// …
],
// µÚ¶þ¸öÊý¾Ý¿â
‘mysql2’ => [
‘driver’ => ‘mysql’,
‘host’ => env(‘DB_HOST2’, ‘127.0.0.1’),
// …
],
],
Ä£×ÓÉèÖÃ
ÔÚLaravelÖУ¬Ã¿¸öÊý¾Ý¿âÅþÁ¬¶¼ÐèÒªÖÁÉÙÒ»¸öÊý¾Ý¿âÄ£×ÓÀ´»á¼ûËü¡£ÎÒÃÇÐèҪΪÿ¸öÊý¾Ý¿âÅþÁ¬½¨ÉèÒ»¸öEloquentÄ£×Ó¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔ½¨ÉèÒ»¸öеÄÄ£×ÓÀ´»á¼ûÎÒÃǸոÕÌí¼ÓµÄ¡°mysql2¡±ÅþÁ¬£º
class Mysql2Model extends Model
{
protected $connection = ‘mysql2’;
protected $table = ‘users’;
// …
}
¸ÃÄ£×ÓÖ¸¶¨Ê¹Óá°mysql2¡±ÅþÁ¬£¬²¢»á¼ûÒ»¸öÃûΪ¡°users¡±µÄ±í¡£
ÔÚ¿ØÖÆÆ÷ÖÐʹÓöà¸öÊý¾Ý¿âÅþÁ¬
ÔÚLaravel¿ØÖÆÆ÷ÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃÿ¸öÊý¾Ý¿âÅþÁ¬µÄ²î±ðÄ£×ÓÀ´ÅþÁ¬¶à¸öÊý¾Ý¿â¡£ÀýÈ磬ÏÂÃæµÄ´úÂ뽫´ÓÁ½¸ö²î±ðµÄÊý¾Ý¿âÖÐÑ¡ÔñÓû§¼Í¼£¬²¢½«ËüÃǺϲ¢µ½Í³Ò»¸öÊý×éÖУº
use AppUser;
use AppMysql2Model;
public function index()
{
// ´ÓĬÈÏÊý¾Ý¿âÖлñÈ¡Óû§Êý¾Ý
$users1 = User::all()->toArray();
// ´ÓµÚ¶þ¸öÊý¾Ý¿âÖлñÈ¡Óû§Êý¾Ý
$users2 = Mysql2Model::all()->toArray();
// ºÏ²¢Á½¸öЧ¹ûÊý×é
$users = array_merge($users1, $users2);
// …
}
ÎÒÃÇ¿ÉÒÔʹÓÃEloquentÀ´»á¼ûµÚÒ»¸öÊý¾Ý¿âÖеÄUserÄ£×Ó£¬È»ºóʹÓÃMysql2Model»á¼ûµÚ¶þ¸öÊý¾Ý¿âÖеÄÏà¹ØÄ£×Ó¡£È»ºó£¬ÎÒÃÇ¿ÉÒÔ½«Á½¸öЧ¹ûÊý×éºÏ²¢ÆðÀ´²¢¾ÙÐкóÐøÊý¾Ý´¦Àí¡£
ÔÚÅÌÎʹ¹½¨Æ÷ÖÐʹÓöà¸öÅþÁ¬
ÔÚLaravelµÄÅÌÎʹ¹½¨Æ÷ÖУ¬ÎÒÃÇ¿ÉÒÔʹÓá°connection¡±ÒªÁìÀ´Ö¸¶¨Ê¹ÓÃÄĸöÊý¾Ý¿âÅþÁ¬¡£ÀýÈ磬ÏÂÃæµÄ´úÂëʹÓõڶþ¸öÊý¾Ý¿âÅþÁ¬´ÓÒ»¸öÃûΪ¡°users¡±µÄ±íÖÐÑ¡ÔñËùÓÐ×ֶεļͼ£º
use IlluminateSupportFacadesDB;
$users = DB::connection(‘mysql2’)->table(‘users’)->get();
ÔÚÕâ¸öÀý×ÓÖУ¬ÎÒÃÇʹÓÃDBÀàÀ´Ö¸¶¨Ê¹Óá°mysql2¡±ÅþÁ¬£¬È»ºóʹÓÃÅÌÎʹ¹½¨Æ÷¡°table¡±ÒªÁì´ÓÃûΪ¡°users¡±µÄ±íÖлñÈ¡ËùÓеļͼ¡£
×ܽ᣺
LaravelÖ§³Ö¶à¸öÊý¾Ý¿âÅþÁ¬£¬ÎÒÃÇ¿ÉÒÔʹÓÃLaravelµÄEloquent ORMºÍDatabase Query BuilderÀ´ÅþÁ¬¶à¸öÊý¾Ý¿â¡£ÎÒÃÇ¿ÉÒÔͨ¹ýÉèÖÃÎļþ¡¢Ä£×Ó¡¢¿ØÖÆÆ÷ÒÔ¼°ÅÌÎʹ¹½¨Æ÷À´Ê¹Óòî±ðµÄÊý¾Ý¿âÅþÁ¬£¬²¢¾ÙÐÐÊý¾ÝµÄ½»»¥¡£ ÕâʹµÃLaravelÔÚÊý¾ÝÖÎÀí·½Ãæ±äµÃÔ½·¢Ç¿Ê¢ºÍÎÞа£¬ÕâÒ²ÊÇÕâ¸ö¿ò¼ÜÔÆÔÆÊ¢ÐеÄÒ»¸öÔµ¹ÊÔÓÉ¡£
ÒÔÉϾÍÊÇlaravelÄܲ»¿É½ÓÁ½¸öÊý¾Ý¿âµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡