[转] 使用 Laravel4 创建博客(一):Models and Seeding

本文将利用 Laravel4 创建一个博客程序,包括以下几点功能:

在主页显示文章及“阅读更多”的帖子链接。

用户将能够搜索文章。

显示文章的评论。

允许用户发表评论。

管理员可以对文章和评论执行CRUD操作。

管理员将能够审核评论。

Laravel快速安装和设置

如果你还没有安装Laravel 4,可以按照下面的步骤安装并设置Laravel 4:

1、安装Laravel 4。具体步骤及命令参考这里http://laravel.com/docs/installation
2、使用MySQL客户端创建数据库
┌─[usm4n@usm4n-desktop]―[~]
└─•mysql -u root -p
Enter password: 
mysql> create database laravel;
Query OK, 1 row affected (0.00 sec)

3、在/app/config/database.php中配置数据库
'mysql' => array(
'driver'    => 'mysql',
'host'      => 'localhost',
'database'  => 'laravel',
'username'  => 'root',
'password'  => 'very_secret_password',
'charset'   => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix'    => '',
),

创建数据库

这里,我们使用Laravel数据库迁移为我们的博客创建数据库。我们分别创建posts和comments表来存放文章及评论。

快速提示 :

我们使用artisan migrate:make create_tablename_table和artisan migrate命令分别创建和运行迁移。

创建posts表:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreatePostsTable extends Migration {

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('posts', function(Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('read_more');
        $table->text('content');
        $table->unsignedInteger('comment_count');
        $table->timestamps();
        $table->engine = 'MyISAM';
    });
    DB::statement('ALTER TABLE posts ADD FULLTEXT search(title, content)');
}
/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('posts', function(Blueprint $table) {
        $table->dropIndex('search');
        $table->drop();
    });
}
}
?>

注意,我使用了 $table->engine='MyISAM' 并使用title和 content列添加复合全文索引 。这样我们就可以在posts表中使用MySQL全文搜索。

创建comments表:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateCommentsTable extends Migration {

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('comments', function(Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('post_id');
        $table->string('commenter');
        $table->string('email');
        $table->text('comment');
        $table->boolean('approved');
        $table->timestamps();
    });
}
/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('comments');
}

}
?>

post_id字段将帮助我们使用Eloquent ORM定义一对多的关系。 使用comments表的approved字段控制评论允许的范围。在验证时我们将覆盖users表。

使用Eloquent ORM创建Models

Laravel自带的Eloquent ORM为我们在操作数据库时提供了一个美观、简洁的ActiveRecord。数据库中每张表都有一个与他对应的Model。

我们使用表名来作为Eloqent Model的名字,这个规则可以帮助我们很容易的找到Eloqent Model所对应的表,如模型的名称为post的Eloqent使用名称为post的数据表。

下面是Post和Comment的Models:
<?php
// file: app/models/Post.php
class Post extends Eloquent {

public function comments()
{
    return $this->hasMany('Comment');
}

}
// file: app/models/Comment.php
class Comment extends Eloquent {

public function post()
{
    return $this->belongsTo('Post');
}
}
?>

Seeding 数据表

我们将使用PostCommentSeeder类来填充posts和comments表。

快速提示:

我们使用artisan db:seed命令Seeding数据库。

下面是PostCommentSeeder类的代码:
<?php

class PostCommentSeeder extends Seeder {

public function run()
{
    $content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.
                Praesent vel ligula scelerisque, vehicula dui eu, fermentum velit.
                Phasellus ac ornare eros, quis malesuada augue. Nunc ac nibh at mauris dapibus fermentum.
                In in aliquet nisi, ut scelerisque arcu. Integer tempor, nunc ac lacinia cursus,
                mauris justo volutpat elit,
                eget accumsan nulla nisi ut nisi. Etiam non convallis ligula. Nulla urna augue,
                dignissim ac semper in, ornare ac mauris. Duis nec felis mauris.';
    for( $i = 1 ; $i <= 20 ; $i++ )
    {
        $post = new Post;
        $post->title = "Post no $i";
        $post->read_more = substr($content, 0, 120);
        $post->content = $content;
        $post->save();

        $maxComments = mt_rand(3,15);
        for( $j = 1 ; $j <= $maxComments; $j++)
        {
            $comment = new Comment;
            $comment->commenter = 'xyz';
            $comment->comment = substr($content, 0, 120);
            $comment->email = 'xyz@xmail.com';
            $comment->approved = 1;
            $post->comments()->save($comment);
            $post->increment('comment_count');
        } 
    }
}
}
?>

外循环里,每次迭代都创建一个新的Post Model并保存title, read_more, content属性,内循环每次都创建Comment Model,并在增加Post表中comment_count数值。

“artisan tinker” 命令

Artisan CLI工具为我们提供了一种简单的方法:用命令行与Laravel应用程序进行交互。我们使用artisan tinker命令来使用交互式shell。 下面我们使用一些测试数据来练习一些Eloquent查询。
┌─[usm4n@usm4n-desktop]―[~]
└─•artisan tinker
>

使用Find()查询ID
$post = Post::find(2);
$post->setHidden(['content','read_more','updated_at']);
echo $post;
{"id":"2","title":"Post no 2","comment_count":"7","created_at":"2014-01-06 09:43:44"}

使用take() 和 skip()
$post = Post::skip(5)->take(2)->get();
foreach($post as $value) echo "post id:$value->id ";
post id:6 post id:7

使用select() 和 first()
$post = Post::select('id','title')->first();
echo $post;
{"id":"1","title":"Post no 1"}

使用where() 和 select()
$post = Post::select('id','title')->where('id','=',10)->first();
echo $post;
{"id":"10","title":"Post no 10"}

使用动态属性获取相关记录
$post = Post::find(4);
echo $post->comments[0]->commenter;

从子Model获取父记录
$comment = Comment::find(1);
echo $comment->post->title;
Post no 1

0 个评论

要回复文章请先登录注册