• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Laravel 五 基础(十一)- Eloquent 关系

php 搞代码 4年前 (2022-01-24) 24次浏览 已收录 0个评论

Laravel 5 基础(十一)- Eloquent 关系

一个用户可能有多个文章,一个文章是某个用户书写的,这就是关系。同样文章中可能包含多个 TAG,而一个 TAG 可能关联多个文章。

在项目中,我们已经有了 User.php,也就是用户模型,查看一下,相当简单。我们希望直接使用 $user->articles() 的形式获取全部文章,让我们修改 user 模型:

<code>    public function articles() {        return $this->hasMany('App\Article');    }</code>

但是我们仅仅完成了关系中的一端,让我们来处理另一端。我们希望的形式是 $article->user() ,让我们修改 article 模型。

<code>    public function user() {        return $this->belongsTo('App\User');    }</code>

在我们的数据库中,文章模型没有用户的外键,我们需要设置,修改 create_article_table.php

<code>		Schema::create('articles', function(Blueprint $table)		{			$table->increments('id');<p>+本文来源gao!%daima.com搞$代*!码9网(</p><strong>搞gaodaima代码</strong>            //指定外键列            $table->integer('user_id')->unsigned();            $table->string('title');            $table->text('body');            $table->timestamp('published_at');			$table->timestamps();            //生成外键            $table->foreign('user_id')                ->references('id')                ->on('users')                ->onDelete('cascade');		});</code>

因为我们只是在开发阶段,还没有上线运行,我们可以直接修改数据库迁移文件,回滚然后迁移即可,但是如果上线运行的话,应该新建一个迁移。

<code>php artisan migrate:refresh#输出信息Rolled back: 2015_03_28_050138_create_article_tableRolled back: 2014_10_12_100000_create_password_resets_tableRolled back: 2014_10_12_000000_create_users_tableNothing to rollback.Migrated: 2014_10_12_000000_create_users_tableMigrated: 2014_10_12_100000_create_password_resets_tableMigrated: 2015_03_28_050138_create_article_tableMigrated: 2015_03_28_051200_add_excerpt_to_articels_table</code>

现在让我们使用 tinker 来创建一个用户。

<code>php artisan tinkerPsy Shell v0.4.1 (PHP 5.4.16 — cli) by Justin Hileman#下面是执行过程>>> $user = new App\User;=>  {}>>> $user->name = 'zhang jinglin';=> "zhang jinglin">>> $user->email = '[email protected]';=> "[email protected]">>> $user->password = bcrypt('pass');=> "$2y$10$Nbl2b9wqd.rXqKEsd3pRSOoIyFAFIhbqf71BufwDfS3Guv21SlEx2">>> $user->save();=> true>>> App\User::first()->toArray();=> [       "id"         => "1",       "name"       => "zhang jinglin",       "email"      => "[email protected]",       "created_at" => "2015-03-31 03:24:55",       "updated_at" => "2015-03-31 03:24:55"   ]>>> </code>

现在我们需要新发布的文章和用户关联,我们暂时先修改 form_partial.blade.php 来隐藏一个用户id,只是暂时:

<code>{{--临时处理--}}{!! Form::hidden('user_id', 1) !!}</code>

同时要修改模型的 $fillabel 属性,以便我们的 Mass Assisment。

<code>	protected $fillable = [        'title',        'body',        'published_at',        'user_id' //临时设置    ];</code>

OK,添加一个文章。我们使用 tinker 来查看一下。

<code>php artisan tinkerPsy Shell v0.4.1 (PHP 5.4.16 — cli) by Justin Hileman>>> App\Article::first()->toArray();=> [       "id"           => "1",       "user_id"      => "1",       "title"        => "User 1 Article",       "body"         => "User 1 Body",       "published_at" => "2015-03-31 08:00:00",       "created_at"   => "2015-03-31 04:17:58",       "updated_at"   => "2015-03-31 04:17:58",       "excerpt"      => null   ]#获取用户>>> $user = App\User::first();=>  {       id: "1",       name: "zhang jinglin",       email: "[email protected]",       created_at: "2015-03-31 03:24:55",       updated_at: "2015-03-31 03:24:55"   }#获取用户文章>>> $user->articles()->toArray();BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::toArray()'>>> $user->articles->toArray();=> [       [           "id"           => "1",           "user_id"      => "1",           "title"        => "User 1 Article",           "body"         => "User 1 Body",           "published_at" => "2015-03-31 08:00:00",           "created_at"   => "2015-03-31 04:17:58",           "updated_at"   => "2015-03-31 04:17:58",           "excerpt"      => null       ]   ]   #为什么使用 $user->articles 而不是 #user->articles()?#事实上,$user->articles()返回的是关系,如果你想用 articles() 你需要这样用>>> $user->articles()->get()->toArray();=> [       [           "id"           => "1",           "user_id"      => "1",           "title"        => "User 1 Article",           "body"         => "User 1 Body",           "published_at" => "2015-03-31 08:00:00",           "created_at"   => "2015-03-31 04:17:58",           "updated_at"   => "2015-03-31 04:17:58",           "excerpt"      => null       ]   ]   #你只能使用 articles() 来进行下一步的工作,比如下面的查询$user->articles()->where('title', 'User 1 Article')->get();#我们也可以通过 article 获取 user>>> $article = App\Article::first();=>  {       id: "1",       user_id: "1",       title: "User 1 Article",       body: "User 1 Body",       published_at: "2015-03-31 08:00:00",       created_at: "2015-03-31 04:17:58",       updated_at: "2015-03-31 04:17:58",       excerpt: null   }>>> $article->user;=>  {       id: "1",       name: "zhang jinglin",       email: "[email protected]",       created_at: "2015-03-31 03:24:55",       updated_at: "2015-03-31 03:24:55"   }>>> </code>
1楼findgor
讲下 后台图片上传吧。就如上传用户头像。表单编辑提交,MVC怎么写的。框架看不明白。

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Laravel 五 基础(十一)- Eloquent 关系

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址