search
HomeBackend DevelopmentPHP TutorialLaravel 五 基础(十一)- Eloquent 关系

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

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

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

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

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

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

在我们的数据库中,文章模型没有用户的外键,我们需要设置,修改 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>

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

<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;=> <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>

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

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

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

<code>	protected $fillable = [        &#39;title&#39;,        &#39;body&#39;,        &#39;published_at&#39;,        &#39;user_id&#39; //临时设置    ];</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();=> <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>
1楼findgor
讲下 后台图片上传吧。就如上传用户头像。表单编辑提交,MVC怎么写的。框架看不明白。
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software