与 Laravel 5.0 的现有数据库集成
Existing database integration with Laravel 5.0
我是 laravel 的新手。我已经在 phpmyadmin 中设计了整个数据库。现在我想整合Laravel中现有的数据库。有什么办法吗?如果是这样,我是否必须创建模型?
是的,您可以在 laravel 中使用您的数据库,但首先您必须提供您的数据库凭据以允许 framework/Laravel 访问您的数据库。因此,您可以使用 .env
文件或简单地使用 config/database.php
来提供凭据,例如,要使用您的 mySql
数据库,您需要按如下方式设置数据库配置:
'default' => env('DB_CONNECTION', 'mysql'),
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'your_database_name'),
'username' => env('DB_USERNAME', 'your_database_username'),
'password' => env('DB_PASSWORD', 'your_database_password'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
]
那么关于你的第二个问题,是的,你必须为每个 table 创建模型,或者你可以使用 DB
facade 直接从你的控制器进行 运行 查询(不推荐) .例如,要访问您的 posts
table,您可以在 app
文件夹中创建一个 Post
模型,它可能看起来像这样:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
// If your table name is other than posts
// then use this property to tell Laravel
// the table name.
protected $table = 'posts';
}
然后你可以使用这样的东西:
$posts = \App\Post::all(); // Get all posts
$post = \App\Post::find(1); // Get the post with id 1
如果您不想像我上面创建的那样使用 Eloquent 模型,那么您可以使用这样的东西:
$posts = \DB::table('posts')->get(); // Get allp posts
这些是帮助您入门的一些基本示例。要了解有关 models/database 用例的更多信息,您应该访问 Laravel website and read the manual (find Database
section and check Query Builder and Eloquent).
我是 laravel 的新手。我已经在 phpmyadmin 中设计了整个数据库。现在我想整合Laravel中现有的数据库。有什么办法吗?如果是这样,我是否必须创建模型?
是的,您可以在 laravel 中使用您的数据库,但首先您必须提供您的数据库凭据以允许 framework/Laravel 访问您的数据库。因此,您可以使用 .env
文件或简单地使用 config/database.php
来提供凭据,例如,要使用您的 mySql
数据库,您需要按如下方式设置数据库配置:
'default' => env('DB_CONNECTION', 'mysql'),
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'your_database_name'),
'username' => env('DB_USERNAME', 'your_database_username'),
'password' => env('DB_PASSWORD', 'your_database_password'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
]
那么关于你的第二个问题,是的,你必须为每个 table 创建模型,或者你可以使用 DB
facade 直接从你的控制器进行 运行 查询(不推荐) .例如,要访问您的 posts
table,您可以在 app
文件夹中创建一个 Post
模型,它可能看起来像这样:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
// If your table name is other than posts
// then use this property to tell Laravel
// the table name.
protected $table = 'posts';
}
然后你可以使用这样的东西:
$posts = \App\Post::all(); // Get all posts
$post = \App\Post::find(1); // Get the post with id 1
如果您不想像我上面创建的那样使用 Eloquent 模型,那么您可以使用这样的东西:
$posts = \DB::table('posts')->get(); // Get allp posts
这些是帮助您入门的一些基本示例。要了解有关 models/database 用例的更多信息,您应该访问 Laravel website and read the manual (find Database
section and check Query Builder and Eloquent).