Home Backend Development PHP Tutorial Laravel 五 基础(十一)- Eloquent 关系

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

Jun 13, 2016 pm 12:17 PM
gt quot user

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

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

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

<code>    public function articles() {        return $this->hasMany(&#39;App\Article&#39;);    }</code>
Copy after login

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

<code>    public function user() {        return $this->belongsTo(&#39;App\User&#39;);    }</code>
Copy after login

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

<code>		Schema::create(&#39;articles&#39;, function(Blueprint $table)		{			$table->increments(&#39;id&#39;);            //指定外键列            $table->integer(&#39;user_id&#39;)->unsigned();            $table->string(&#39;title&#39;);            $table->text(&#39;body&#39;);            $table->timestamp(&#39;published_at&#39;);			$table->timestamps();            //生成外键            $table->foreign(&#39;user_id&#39;)                ->references(&#39;id&#39;)                ->on(&#39;users&#39;)                ->onDelete(&#39;cascade&#39;);		});</code>
Copy after login

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

<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>
Copy after login

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

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

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

<code>{{--临时处理--}}{!! Form::hidden(&#39;user_id&#39;, 1) !!}</code>
Copy after login

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

<code>	protected $fillable = [        &#39;title&#39;,        &#39;body&#39;,        &#39;published_at&#39;,        &#39;user_id&#39; //临时设置    ];</code>
Copy after login

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();=> <App\User #0000000051cbb9d70000000073e11a3e> {       id: "1",       name: "zhang jinglin",       email: "[email&#160;protected]",       created_at: "2015-03-31 03:24:55",       updated_at: "2015-03-31 03:24:55"   }#获取用户文章>>> $user->articles()->toArray();BadMethodCallException with message &#39;Call to undefined method Illuminate\Database\Query\Builder::toArray()&#39;>>> $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(&#39;title&#39;, &#39;User 1 Article&#39;)->get();#我们也可以通过 article 获取 user>>> $article = App\Article::first();=> <App\Article #0000000051cbb9d60000000073e11a3e> {       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;=> <App\User #0000000051cbb92d0000000073e11a3e> {       id: "1",       name: "zhang jinglin",       email: "[email&#160;protected]",       created_at: "2015-03-31 03:24:55",       updated_at: "2015-03-31 03:24:55"   }>>> </code>
Copy after login
1楼findgor
讲下 后台图片上传吧。就如上传用户头像。表单编辑提交,MVC怎么写的。框架看不明白。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

How to solve the problem of docker mounting directory permissions How to solve the problem of docker mounting directory permissions Feb 29, 2024 am 10:04 AM

In Docker, the permission problem of the mounting directory can usually be solved by the following method: adding permission-related options when using the -v parameter to specify the mounting directory. You can specify the permissions of the mounted directory by adding: ro or :rw after the mounted directory, indicating read-only and read-write permissions respectively. For example: dockerrun-v/host/path:/container/path:roimage_name Define the USER directive in the Dockerfile to specify the user running in the container to ensure that operations inside the container comply with permission requirements. For example: FROMimage_name#CreateanewuserRUNuseradd-ms/bin/

Is watch4pro better or gt? Is watch4pro better or gt? Sep 26, 2023 pm 02:45 PM

Watch4pro and gt each have different features and applicable scenarios. If you focus on comprehensive functions, high performance and stylish appearance, and are willing to bear a higher price, then Watch 4 Pro may be more suitable. If you don’t have high functional requirements and pay more attention to battery life and reasonable price, then the GT series may be more suitable. The final choice should be decided based on personal needs, budget and preferences. It is recommended to carefully consider your own needs before purchasing and refer to the reviews and comparisons of various products to make a more informed choice.

请教怎么修改url某一参数的参数值呢?是要拆开了再拼回去吗 请教怎么修改url某一参数的参数值呢?是要拆开了再拼回去吗 Jun 13, 2016 am 10:24 AM

请问如何修改url某一参数的参数值呢?是要拆开了再拼回去吗?那么请问如何修改url某一参数的参数值呢?是要拆开了再拼回去吗?http://127.0.0.1/myo/newuser.php?mod=search&type=fastone比如现在我要修改mod=new要怎么做呢?------解决方案--------------------发送了请求

How to optimize iPad battery life with iPadOS 17.4 How to optimize iPad battery life with iPadOS 17.4 Mar 21, 2024 pm 10:31 PM

How to Optimize iPad Battery Life with iPadOS 17.4 Extending battery life is key to the mobile device experience, and the iPad is a good example. If you feel like your iPad's battery is draining too quickly, don't worry, there are a number of tricks and tweaks in iPadOS 17.4 that can significantly extend the run time of your device. The goal of this in-depth guide is not just to provide information, but to change the way you use your iPad, enhance your overall battery management, and ensure you can rely on your device for longer without having to charge it. By adopting the practices outlined here, you take a step toward more efficient and mindful use of technology that is tailored to your individual needs and usage patterns. Identify major energy consumers

See all articles