空间的根目录定死了,但是laravel 获取根目录的index一定要放public,怎么办

空间的根目录定死了,但是laravel的index一定要放public,怎么办_百度知道
空间的根目录定死了,但是laravel的index一定要放public,怎么办
$app&=&nbsp.ico移到外面(与app.'require_once&vendor文件夹同层)2.&#39./;bootstrap,&nbsp.php'require_once&nbsp.phprequire&nbsp1.htaccess.修改index.php'$app&__DIR__,&/.'../bootstrap/index./bootstrap/;public.php&#39.首先把,&/bootstrap/__DIR__,&__DIR__./public目录下把;//改成以下require&nbsp,&nbsp.;=&/bootstrap/autoload.php'__DIR__;.'
其他类似问题
为您推荐:
根目录的相关知识
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁详解PHP的Laravel框架中Eloquent对象关系映射使用
作者:JohnLui
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了PHP的Laravel框架中Eloquent对象关系映射使用,重点讲述了Eloquent的数据模型间关系,需要的朋友可以参考下
零、什么是 Eloquent
Eloquent 是 Laravel 的 'ORM',即 'Object Relational Mapping',对象关系映射。ORM 的出现是为了帮我们把对数据库的操作变得更加地方便。
Eloquent 让一个 'Model类' 对应一张数据库表,并且在底层封装了很多 'function',可以让 Model 类非常方便地调用。
来看一段如下代码:
class Article extends \Eloquent {
protected $fillable = [];
'protected $fillable = [];' 这一行代码在这里没有任何价值,是 generator 自动生成的,在此我们不做讨论。
这个类简直再简单不过了,没有指定命名空间,没有构造函数,如果那一行没有意义的代码也不算上的话,这个文件就只有两个有实际意义的东西: 'Article' 和 '\Eloquent'。没错,Eloquent 就是这么屌炸天,只需要继承一下 Eloquent 类,就可以干 'first() find() where() orderBy()' 等非常非常多的事情,这就是面向对象的强大威力。
一、Eloquent 基本用法
Eloquent 中文文档在:http://laravel-china.org/docs/eloquent
废话不多说,下面我将直接展示 Eloquent 的几种常见用法的代码。
找到 id 为 2 的文章打印其标题
$article = Article::find(2);
echo $article-&
查找标题为“我是标题”的文章,并打印 id
$article = Article::where('title', '我是标题')-&first();
echo $article-&
查询出所有文章并循环打印出所有标题
$articles = Article::all(); // 此处得到的 $articles 是一个对象集合,可以在后面加上 '-&toArray()' 变成多维数组。
foreach ($articles as $article) {
echo $article-&
查找 id 在 10~20 之间的所有文章并打印所有标题
$articles = Article::where('id', '&', 10)-&where('id', '&', 20)-&get();
foreach ($articles as $article) {
echo $article-&
查询出所有文章并循环打印出所有标题,按照 updated_at 倒序排序
$articles = Article::where('id', '&', 10)-&where('id', '&', 20)-&orderBy('updated_at', 'desc')-&get();
foreach ($articles as $article) {
echo $article-&
基础使用要点
1. 每一个继承了 Eloquent 的类都有两个 '固定用法' 'Article::find($number)' 'Article::all()',前者会得到一个带有数据库中取出来值的对象,后者会得到一个包含整个数据库的对象合集。
2. 所有的中间方法如 'where()' 'orderBy()' 等都能够同时支持 '静态' 和 '非静态链式' 两种方式调用,即 'Article::where()...' 和 'Article::....-&where()'。
3. 所有的 '非固定用法' 的调用最后都需要一个操作来 '收尾',本片教程中有两个 '收尾操作':'-&get()' 和 '-&first()'。
二、中间操作流
Builder 这个单词可以直译成构造器,但是“中间操作流”更容易理解,因为数据库操作大部分时候都是链式操作的。
中间操作流,请看代码:
Article::where('id', '&', 10)-&where('id', '&', 20)-&orderBy('updated_at', 'desc')-&get();
这段代码的 `::where()-&where()-&orderBy()` 就是中间操作流。中间操作流用面向对象的方法来理解,可以总结成一句话:
创建一个对象,并不断修改它的属性,最后用一个操作来触发数据库操作。
如何找到中间操作流的蛛丝马迹
中间操作流这个东西,文档里几乎没有任何有价值的信息,那么,我们该怎么找出这个玩意儿呢?很简单,使用以下代码:
$builder = Article::where('title', "我是标题")-&
然后你就会看到下面的错误:
为什么会出现错误?因为 `Article::where()` 了之后依然是 `Builder` 对象,还不是 `Article` 对象,不能直接取 `title`。
“终结者”方法
所谓 “终结者” 方法,指的是在 N 个中间操作流方法对某个 Eloquent 对象进行加工以后,触发最终的数据库查询操作,得到返回值。
`first()` `get()` `paginate()` `count()` `delete()` 是用的比较多的一些 “终结者” 方法,他们会在中间操作流的最后出现,把 SQL 打给数据库,得到返回数据,经过加工返回一个 Article 对象或者一群 Article 对象的集合。
复杂用法示例
Article::where('id', '&', '100')-&where('id', '&', '200')-&orWhere('top', 1)-&belongsToCategory()-&where('category_level', '&', '1')-&paginate(10);
三、模型间关系(关联)
1.一对一关系
顾名思义,这描述的是两个模型之间一对一的关系。这种关系是不需要中间表的。
假如我们有两个模型:User 和 Account,分别对应注册用户和消费者,他们是一对一的关系,那么如果我们要使用 Eloquent 提供的一对一关系方法,表结构应该是这样的:
user: id ... ... account_id
account: id ... ... user_id
假设我们需要在 User 模型中查询对应的 Account 表的信息,那么代码应该是这样的。 `/app/models/User.php`:
class User extends Eloquent {
protected $table = 'users';
public function hasOneAccount()
return $this-&hasOne('Account', 'user_id', 'id');
然后,当我们需要用到这种关系的时候,该如何使用呢?如下:
$account = User::find(10)-&hasOneA
此时得到的 `$account` 即为 `Account` 类的一个实例。
这里最难的地方在于后面的两个 foreign_key 和 local_key 的设置,大家可以就此记住:在 User 类中,无论 hasOne 谁,第二个参数都是 `user_id`,第三个参数一般都是 `id`。由于前面的 `find(10)` 已经锁定了 id = 10,所以这段函数对应的 SQL 为: `select * from account where user_id=10`。
这段代码除了展示了一对一关系该如何使用之外,还传达了三点信息,也是我对于大家使用 Eloquent 时候的建议:
(1). 每一个 Model 中都指定表名
(2). has one account 这样的关系写成 `hasOneAccount()` 而不是简单的 `account()`
(3). 每次使用模型间关系的时候都写全参数,不要省略
相应的,如果使用 belongsTo() 关系,应该这么写:
class Account extends Eloquent {
protected $table = 'accounts';
public function belongsToUser()
return $this-&belongsTo('User', 'user_id', 'id');
2.一对多关系
学会了前面使用一对一关系的基础方法,后面的几种关系就简单多了。
我们引入一个新的Model:Pay,付款记录。表结构应该是这样的:
user: id ... ...
pay: id ... ... user_id
User 和 Pay 具有一对多关系,换句话说就是一个 User 可以有多个 Pay,这样的话,只在 Pay 表中存在一个 `user_id` 字段即可。 `/app/models/User.php`:
class User extends Eloquent {
protected $table = 'users';
public function hasManyPays()
return $this-&hasMany('Pay', 'user_id', 'id');
然后,当我们需要用到这种关系的时候,该如何使用呢?如下:
$accounts = User::find(10)-&hasManyPays()-&get();
此时得到的 `$accounts` 即为 `Illuminate\Database\Eloquent\Collection` 类的一个实例。大家应该也已经注意到了,这里不是简单的 `-& hasOneAccount` 而是 `-&hasManyPays()-&get()`,为什么呢?因为这里是 `hasMany`,操作的是一个对象集合。
相应的 belongsTo() 的用法跟上面一对一关系一样:
class Pay extends Eloquent {
protected $table = 'pays';
public function belongsToUser()
return $this-&belongsTo('User', 'user_id', 'id');
3.多对多关系
多对多关系和之前的关系完全不一样,因为多对多关系可能出现很多冗余数据,用之前自带的表存不下了。
我们定义两个模型:Article 和 Tag,分别表示文章和标签,他们是多对多的关系。表结构应该是这样的:
article: id ... ...
tag: id ... ...
article_tag: article_id tag_id
在 Model 中使用:
class Tag extends Eloquent {
protected $table = 'tags';
public function belongsToManyArticle()
return $this-&belongsToMany('Article', 'article_tag', 'tag_id', 'article_id');
需要注意的是,第三个参数是本类的 id,第四个参数是第一个参数那个类的 id。
使用跟 hasMany 一样:
$tagsWithArticles = Tag::take(10)-&get()-&belongsToManyArticle()-&get();
这里会得到一个非常复杂的对象,可以自行 `var_dump()`。跟大家说一个诀窍,`var_dump()` 以后,用 Chrome 右键 “查看源代码”,就可以看到非常整齐的对象/数组展开了。
在这里给大家展示一个少见用法(奇技淫巧):
public function parent_video()
return $this-&belongsToMany($this, 'video_hierarchy', 'video_id', 'video_parent_id');
public function children_video()
return $this-&belongsToMany($this, 'video_hierarchy', 'video_parent_id', 'video_id');
对,你没有看错,可以 belongsToMany 自己。
Eloquent 还提供 “远层一对多关联”、“多态关联” 和 “多态的多对多关联” 这另外三种用法,经过上面的学习,我们已经掌握了 Eloquent 模型间关系的基本概念和使用方法,剩下的几种不常用的方法就留到我们用到的时候再自己探索吧。
重要技巧:关系预载入
你也许已经发现了,在一对一关系中,如果我们需要一次性查询出10个 User 并带上对应的 Account 的话,那么就需要给数据库打 1 + 10 条 SQL,这样性能是很差的。我们可以使用一个重要的特性,关系预载入:http://laravel-china.org/docs/eloquent#eager-loading
直接上代码:
$users = User::with('hasOneAccount')-&take(10)-&get()
这样生成的 SQL 就是这个样子的:
select * from account where id in (1, 2, 3, ... ...)
这样 1 + 10 条 SQL 就变成了 1 + 1 条,性能大增。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具Hello,好久不见啦
最近作者实在是要忙飞了,一直也没更新BLOG
今天来给大家说说Laravel&框架的URL中PUBLIC如何移除吧
首先说两句废话,第一就是 Why Laravel?
Larvael 早在作者还是留学狗就听周围的老外同学巴拉巴拉啦
回国之后发现周围的做开发都朋友都在用 ThinkPHP,Yii
于是本人自命清高 不愿意跟别人一样 (in fact 装逼)美特斯邦威穿多了-.-&
就开始研究Laravel框架为手头的项目做准备。
这是第一点第二就是通过搜索得知Laravel确实应用的比较多,下面上reference
好的第一名居然是Larvael,当然这只是Sitpoint网站的一个调查不能说明什么
但是作者用过之后确实为Larvael点了个赞,用过都说好.
再不说正题可能有人就要打人了
这篇blog为初学者量身定制,laravel下载的通用全部过程
另外解决标题的问题
自然不用说了去Larvael 官网下载页面发现有一个一键安装包
对就是一键安装包,作者在这里不给你们讲什么用composer安装
因为有些同学不会用composer 总不能因为不会用composer就不学laravel了吧
首先选择一个版本下载,完成之后会有一个laravel-version(版本)这么一个压缩文件
解压到apache目录下的htdocs文件夹下并改名为Larvael当然了改成什么随便你
作者这里就改成了Larvael
访问localhost:端口/laravel/public 之后你会发现Larvael的主界面向你招手了
但是细心的同学发现这里总是有一个/public无论再加什么/url他都会存在 很是烦人不能以后项目上线
就给人家一个这样的URL吧&
这里作者告诉你如何删去PUBLIC
其实很简单只需要laravel/server.php
改名为index.php
并且将public目录下的.htaccess拷贝到Larvael根目下
再去访问localhost/Larvael/就会发现不需要加上public这个烦人的东西了
最后请小心如果你的CSS JS FONT的文件有用的话 请把他们也拷贝到Larvael的根目录下
否则你会发现你的css js都404啦 千万要记住.
这里作者补充一句 只可在测试环境下这样使用,否则真实环境会有安全问题!
好的今天的blog就写到这里边,一样希望对想删除URL里面public的朋友们有帮助&
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:1370次
排名:千里之外Laravel学习笔记之Seeder填充数据小技巧
说明:本文主要聊一聊Laravel测试数据填充器Seeder的小技巧,同时介绍下Laravel开发插件三件套,这三个插件挺好用哦。同时,作者会将开发过程中的一些截图和代码黏上去,提高阅读效率。备注:在设计个人博客软件时,总会碰到有分类Category、博客Post、给博客贴的标签Tag、博客内容的评论Comment。而且,Category与Post是一对多关系One-Many:一个分类下有很多Post,一个Post只能归属于一个Category;Post与Comment是一对多关系One-Many:一篇博客Post下有很多Comment,一条Comment只能归属于一篇Post;Post与Tag是多对多关系Many-Many:一篇Post有很多Tag,一个Tag下有很多Post。开发环境:Laravel5.2 + MAMP + PHP7 + MySQL5.5开发插件三件套在先聊测试数据填充器seeder之前,先装上开发插件三件套,开发神器。先不管这能干些啥,装上再说。1、barryvdh/laravel-debugbarcomposer require barryvdh/laravel-debugbar --dev2、barryvdh/laravel-ide-helpercomposer require barryvdh/laravel-ide-helper --dev3、mpociot/laravel-test-factory-helpercomposer require mpociot/laravel-test-factory-helper --dev然后在config/app.php文件中填上:/** *Develop Plugin*/BarryvdhDebugbarServiceProvider::class,MpociotLaravelTestFactoryHelperTestFactoryHelperServiceProvider::class,BarryvdhLaravelIdeHelperIdeHelperServiceProvider::class,设计表的字段和关联设计字段按照上文提到的Category、Post、Comment和Tag之间的关系创建迁移Migration和模型Model,在项目根目录输入:php artisan make:model Category -mphp artisan make:model Post -mphp artisan make:model Comment -mphp artisan make:model Tag -m在各个表的迁移migrations文件中根据表的功能设计字段://Category表class CreateCategoriesTable extends Migration{/** * Run the migrations.* * @return void*/ public function up(){ Schema::create('categories', function (Blueprint $table) {$table->increments('id');$table->string('name')->comment('分类名称');$table->integer('hot')->comment('分类热度');$table->string('image')->comment('分类图片');$table->timestamps();});}/** * Reverse the migrations.* * @return void*/ public function down(){Schema::drop('categories');}}//Post表class CreatePostsTable extends Migration{/** * Run the migrations.* * @return void*/ public function up(){ Schema::create('posts', function (Blueprint $table) {$table->increments('id');$table->integer('category_id')->unsigned()->comment('外键');$table->string('title')->comment('标题');$table->string('slug')->unique()->index()->comment('锚点');$table->string('summary')->comment('概要');$table->text('content')->comment('内容');$table->text('origin')->comment('文章来源');$table->integer('comment_count')->unsigned()->comment('评论次数');$table->integer('view_count')->unsigned()->comment('浏览次数');$table->integer('favorite_count')->unsigned()->comment('点赞次数');$table->boolean('published')->comment('文章是否发布');$table->timestamps();//Post表中category_id字段作为外键,与Category一对多关系$table->foreign('category_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');});}/** * Reverse the migrations.* * @return void*/ public function down(){//删除表时要删除外键约束,参数为外键名称 Schema::table('posts', function(Blueprint $tabel){$tabel->dropForeign('posts_category_id_foreign');});Schema::drop('posts');}}//Comment表class CreateCommentsTable extends Migration{/** * Run the migrations.* * @return void*/ public function up(){ Schema::create('comments', function (Blueprint $table) {$table->increments('id');$table->integer('post_id')->unsigned()->comment('外键');$table->integer('parent_id')->comment('父评论id');$table->string('parent_name')->comment('父评论标题');$table->string('username')->comment('评论者用户名');$table->string('email')->comment('评论者邮箱');$table->string('blog')->comment('评论者博客地址');$table->text('content')->comment('评论内容');$table->timestamps();//Comment表中post_id字段作为外键,与Post一对多关系$table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');});}/** * Reverse the migrations.* * @return void*/ public function down(){//删除表时要删除外键约束,参数为外键名称 Schema::table('comments', function(Blueprint $tabel){$tabel->dropForeign('comments_post_id_foreign');});Schema::drop('comments');}}//Tag表class CreateTagsTable extends Migration{/** * Run the migrations.* * @return void*/ public function up(){ Schema::create('tags', function (Blueprint $table) {$table->increments('id');$table->string('name')->comment('标签名称');$table->integer('hot')->unsigned()->comment('标签热度');$table->timestamps();});}/** * Reverse the migrations.* * @return void*/ public function down(){Schema::drop('tags');}}由于Post表与Tag表是多对多关系,还需要一张存放两者关系的表://多对多关系,中间表的命名laravel默认按照两张表字母排序来的,写成tag_post会找不到中间表php artisan make:migration create_post_tag_table --create=post_tag然后填上中间表的字段:class CreatePostTagTable extends Migration{/** * Run the migrations.* * @return void*/ public function up(){ Schema::create('post_tag', function (Blueprint $table) {$table->increments('id');$table->integer('post_id')->unsigned();$table->integer('tag_id')->unsigned();$table->timestamps();//post_id字段作为外键$table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');//tag_id字段作为外键$table->foreign('tag_id')->references('id')->on('tags')->onUpdate('cascade')->onDelete('cascade');});}/** * Reverse the migrations.* * @return void*/ public function down(){ Schema::table('post_tag', function(Blueprint $tabel){$tabel->dropForeign('post_tag_post_id_foreign');$tabel->dropForeign('post_tag_tag_id_foreign');});Schema::drop('post_tag');}}设计关联写上Migration后,还得在Model里写上关联:class Category extends Model{//Category-Post:One-Many public function posts(){ return $this->hasMany(Post::class);}}class Post extends Model{//Post-Category:Many-One public function category(){ return $this->belongsTo(Category::class);}//Post-Comment:One-Many public function comments(){ return $this->hasMany(Comment::class);}//Post-Tag:Many-Many public function tags(){ return $this->belongsToMany(Tag::class)->withTimestamps();}}class Comment extends Model{//Comment-Post:Many-One public function post(){ return $this->belongsTo(Post::class);}}class Tag extends Model{//Tag-Post:Many-Many public function posts(){ return $this->belongsToMany(Post::class)->withTimestamps();}}然后执行迁移:php artisan migrate数据库中会生成新建表,表的关系如下:Seeder填充测试数据好,在聊到seeder测试数据填充之前,看下开发插件三件套能干些啥,下文中命令可在项目根目录输入php artisan指令列表中查看。1、barryvdh/laravel-ide-helper执行php artisan ide-helper:generate指令前:执行php artisan ide-helper:generate指令后:不仅Facade模式的Route由之前的反白了变为可以定位到源码了,而且输入Config Facade时还方法自动补全auto complete,这个很方便啊。输入指令php artisan ide-helper:models后,看看各个Model,如Post这个Model:&?phpnamespace Ause IlluminateDatabaseEloquentM/** * AppPost* * @property integer $id * @property integer $category_id 外键 * @property string $title 标题 * @property string $slug 锚点 * @property string $summary 概要 * @property string $content 内容 * @property string $origin 文章来源 * @property integer $comment_count 评论次数 * @property integer $view_count 浏览次数 * @property integer $favorite_count 点赞次数 * @property boolean $published 文章是否发布 * @property CarbonCarbon $created_at * @property CarbonCarbon $updated_at * @property-read AppCategory $category * @property-read IlluminateDatabaseEloquentCollection|AppComment[] $comments * @property-read IlluminateDatabaseEloquentCollection|AppTag[] $tags * @method static IlluminateDatabaseQueryBuilder|AppPost whereId($value) * @method static IlluminateDatabaseQueryBuilder|AppPost whereCategoryId($value) * @method static IlluminateDatabaseQueryBuilder|AppPost whereTitle($value) * @method static IlluminateDatabaseQueryBuilder|AppPost whereSlug($value) * @method static IlluminateDatabaseQueryBuilder|AppPost whereSummary($value) * @method static IlluminateDatabaseQueryBuilder|AppPost whereContent($value) * @method static IlluminateDatabaseQueryBuilder|AppPost whereOrigin($value) * @method static IlluminateDatabaseQueryBuilder|AppPost whereCommentCount($value) * @method static IlluminateDatabaseQueryBuilder|AppPost whereViewCount($value) * @method static IlluminateDatabaseQueryBuilder|AppPost whereFavoriteCount($value) * @method static IlluminateDatabaseQueryBuilder|AppPost wherePublished($value) * @method static IlluminateDatabaseQueryBuilder|AppPost whereCreatedAt($value) * @method static IlluminateDatabaseQueryBuilder|AppPost whereUpdatedAt($value) * @mixin Eloquent*/class Post extends Model{//Post-Category:Many-One public function category(){ return $this->belongsTo(Category::class);}//Post-Comment:One-Many public function comments(){ return $this->hasMany(Comment::class);}//Post-Tag:Many-Many public function tags(){ return $this->belongsToMany(Tag::class)->withTimestamps();}}根据迁移到库里的表生成字段属性和对应的方法提示,在控制器里输入方法时会自动补全auto complete字段属性的方法:2、mpociot/laravel-test-factory-helper输入指令php artisan test-factory-helper:generate后,database/factory/ModelFactory.php模型工厂文件会自动生成各个模型对应字段数据。Faker是一个好用的生成假数据的第三方库,而这个开发插件会自动帮你生成这些属性,不用自己写了。&?php$factory->define(AppUser::class, function (FakerGenerator $faker) { return [ 'name' => $faker->name, 'email' => $faker->safeEmail, 'password' => bcrypt(str_random(10)), 'remember_token' => str_random(10),];});$factory->define(AppCategory::class, function (FakerGenerator $faker) { return [ 'name' => $faker->name , 'hot' => $faker->randomNumber() , 'image' => $faker->word ,];});$factory->define(AppComment::class, function (FakerGenerator $faker) { return [ 'post_id' => function () { return factory(AppPost::class)->create()-> } , 'parent_id' => $faker->randomNumber() , 'parent_name' => $faker->word , 'username' => $faker->userName , 'email' => $faker->safeEmail , 'blog' => $faker->word , 'content' => $faker->text ,];});$factory->define(AppPost::class, function (FakerGenerator $faker) { return [ 'category_id' => function () { return factory(AppCategory::class)->create()-> } , 'title' => $faker->word , 'slug' => $faker->slug ,//修改为slug 'summary' => $faker->word , 'content' => $faker->text , 'origin' => $faker->text , 'comment_count' => $faker->randomNumber() , 'view_count' => $faker->randomNumber() , 'favorite_count' => $faker->randomNumber() , 'published' => $faker->boolean ,];});$factory->define(AppTag::class, function (FakerGenerator $faker) { return [ 'name' => $faker->name , 'hot' => $faker->randomNumber() ,];});在聊第三个debugbar插件前先聊下seeder小技巧,用debugbar来帮助查看。Laravel官方推荐使用模型工厂自动生成测试数据,推荐这么写的://先输入指令生成database/seeds/CategoryTableSeeder.php文件: php artisan make:seeder CategoryTableSeeder&?phpuse IlluminateDatabaseSclass CategoryTableSeeder extends Seeder{/** * Run the database seeds.* * @return void*/ public function run(){ factory(AppCategory::class, 5)->create()->each(function($category){$category->posts()->save(factory(AppPost::class)->make());});}}//然后php artisan db:seed执行数据填充但是这种方式效率并不高,因为每一次create()都是一次query,而且每生成一个Category也就对应生成一个Post,当然可以在each()里每一次Category继续foreach()生成几个Post,但每一次foreach也是一次query,效率更差。可以用debugbar小能手看看。先在DatabaseSeeder.php文件中填上这次要填充的Seeder: public function run(){ // $this->call(UsersTableSeeder::class);$this->call(CategoryTableSeeder::class);}在路由文件中写上:Route::get('/artisan', function () { $exitCode = Artisan::call('db:seed'); return $exitC});输入路由/artisan后用debugbar查看执行了15次query,耗时7.11ms:实际上才刚刚输入几个数据呢,Category插入了10个,Post插入了5个。可以用DB::table()->insert()批量插入,拷贝ModelFactory.php中表的字段定义放入每一个表对应Seeder,当然可以有些字段为便利也适当修改对应假数据。class CategoryTableSeeder extends Seeder{/** * Run the database seeds.* * @return void*/ public function run(){// factory(AppCategory::class, 20)->create()->each(function($category){// $category->posts()->save(factory(AppPost::class)->make());// }); $faker = FakerFactory::create(); $datas = []; foreach (range(1, 10) as $key => $value) { $datas[] = [ 'name' => 'category'.$faker->randomNumber() , 'hot' => $faker->randomNumber() , 'image' => $faker->url , 'created_at' => CarbonCarbon::now()->toDateTimeString(), 'updated_at' => CarbonCarbon::now()->toDateTimeString()];}DB::table('categories')->insert($datas);}}class PostTableSeeder extends Seeder{/** * Run the database seeds.* * @return void*/ public function run(){ $faker = FakerFactory::create(); $category_ids = AppCategory::lists('id')->toArray(); $datas = []; foreach (range(1, 10) as $key => $value) { $datas[] = [ 'category_id' => $faker->randomElement($category_ids), 'title' => $faker->word , 'slug' => $faker->slug , 'summary' => $faker->word , 'content' => $faker->text , 'origin' => $faker->text , 'comment_count' => $faker->randomNumber() , 'view_count' => $faker->randomNumber() , 'favorite_count' => $faker->randomNumber() , 'published' => $faker->boolean , 'created_at' => CarbonCarbon::now()->toDateTimeString(), 'updated_at' => CarbonCarbon::now()->toDateTimeString()];}DB::table('posts')->insert($datas);}}class CommentTableSeeder extends Seeder{/** * Run the database seeds.* * @return void*/ public function run(){ $faker = FakerFactory::create(); $post_ids = AppPost::lists('id')->toArray(); $datas = []; foreach (range(1, 50) as $key => $value) { $datas[] = [ 'post_id' => $faker->randomElement($post_ids), 'parent_id' => $faker->randomNumber() , 'parent_name' => $faker->word , 'username' => $faker->userName , 'email' => $faker->safeEmail , 'blog' => $faker->word , 'content' => $faker->text , 'created_at' => CarbonCarbon::now()->toDateTimeString(), 'updated_at' => CarbonCarbon::now()->toDateTimeString()];}DB::table('comments')->insert($datas);}}class TagTableSeeder extends Seeder{/** * Run the database seeds.* * @return void*/ public function run(){ $faker = FakerFactory::create(); $datas = []; foreach (range(1, 10) as $key => $value) { $datas[] = [ 'name' => 'tag'.$faker->randomNumber() , 'hot' => $faker->randomNumber() , 'created_at' => CarbonCarbon::now()->toDateTimeString(), 'updated_at' => CarbonCarbon::now()->toDateTimeString()];}DB::table('tags')->insert($datas);}}class PostTagTableSeeder extends Seeder{/** * Run the database seeds.* * @return void*/ public function run(){ $faker = FakerFactory::create(); $post_ids = AppPost::lists('id')->toArray(); $tag_ids = AppTag::lists('id')->toArray(); $datas = []; foreach (range(1, 20) as $key => $value) { $datas[] = [ 'post_id' => $faker->randomElement($post_ids) , 'tag_id' => $faker->randomElement($tag_ids) , 'created_at' => CarbonCarbon::now()->toDateTimeString(), 'updated_at' => CarbonCarbon::now()->toDateTimeString()];}DB::table('post_tag')->insert($datas);}}在DatabaseSeeder.php中按照顺序依次填上Seeder,顺序不能颠倒,尤其有关联关系的表:class DatabaseSeeder extends Seeder{/** * Run the database seeds.* * @return void*/ public function run(){ // $this->call(UsersTableSeeder::class);$this->call(CategoryTableSeeder::class);$this->call(PostTableSeeder::class);$this->call(CommentTableSeeder::class);$this->call(TagTableSeeder::class);$this->call(PostTagTableSeeder::class);}}输入路由/artisan后,生成了10个Category、10个Post、50个Comments、10个Tag和PostTag表中多对多关系,共有9个Query耗时13.52ms:It is working!!!表的迁移Migration和关联Relationship都已设计好,测试数据也已经Seeder好了,就可以根据Repository模式来设计一些数据库逻辑了。准备趁着端午节研究下Repository模式的测试,PHPUnit结合Mockery包来TDD测试也是一种不错的玩法。M(Model)-V(View)-C(Controller)模式去组织代码,很多时候也未必指导性很强,给Model加一个Repository,给Controller加一个Service,给View加一个Presenter,或许代码结构更清晰。具体可看下面分享的一篇文章。最近一直在给自己充电,研究MySQL,PHPUnit,Laravel,上班并按时打卡,看博客文章,每天喝红牛。很多不会,有些之前没咋学过,哎,头疼。后悔以前读书太少,书到用时方恨少,人丑还需多读书。研究生学习机器人的,本打算以后读博搞搞机器人的(研一时真是这么想真是这么准备的,too young too simple)。现在做PHP小码农了,只因当时看到智能机就激动得不行,决定以后做个码农试试吧,搞不好是条生路,哈哈。读书时觉悟太晚,耗费了青春,其实我早该踏入这条路的嘛,呵呵。Follow My Heart!不扯了,在凌晨两点边听音乐边写博客,就容易瞎感慨吧。。分享下最近发现的一张好图和一篇极赞的文章:文章链接:Laravel的中大型專案架構
最新教程周点击榜
微信扫一扫

我要回帖

更多关于 laravel 根目录 的文章

 

随机推荐