Eloquent是Laravel的原始ActiveRecord是实现的,建立在Laravel的Fluent Query Builder之上的,所以Eloquent类和Fluent类是一样的,能实现复杂的SQL语句和非常直观表达出的表与表之间的关系。本文就以此展开学习,希望对大家有所帮助。
一个用户可能有多个文章,一个文章是某个用户书写的,这就是关系。同样文章中可能包含多个 TAG,而一个 TAG 可能关联多个文章。
在项目中,我们已经有了 User.php,也就是用户模型,查看一下,相当简单。我们希望直接使用 $user->articles() 的形式获取全部文章,让我们修改 user 模型:
public function articles() { return $this->hasMany('App\Article'); }
但是我们仅仅完成了关系中的一端,让我们来处理另一端。我们希望的形式是 $article->user() ,让我们修改 article 模型。
public function user() { return $this->belongsTo('App\User'); }
在我们的数据库中,文章模型没有用户的外键,我们需要设置,修改 create_article_table.php
Schema::create('articles', function(Blueprint $table) { $table->increments('id'); //指定外键列 $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'); });
因为我们只是在开发阶段,还没有上线运行,我们可以直接修改数据库迁移文件,回滚然后迁移即可,但是如果上线运行的话,应该新建一个迁移。
php artisan migrate:refresh #输出信息 Rolled back: 2015_03_28_050138_create_article_table Rolled back: 2014_10_12_100000_create_password_resets_table Rolled back: 2014_10_12_000000_create_users_table Nothing to rollback. Migrated: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_100000_create_password_resets_table Migrated: 2015_03_28_050138_create_article_table Migrated: 2015_03_28_051200_add_excerpt_to_articels_table
现在让我们使用 tinker 来创建一个用户。
php artisan tinker Psy Shell v0.4.1 (PHP 5.4.16 — cli) by Justin Hileman #下面是执行过程 >>> $user = new App\User; => <App\User #000000007f1ad61a000000006497cc4f> {} >>> $user->name = 'zhang jinglin'; => "zhang jinglin" >>> $user->email = 'zjl@example.com'; => "zjl@example.com" >>> $user->password = bcrypt('pass'); => "$2y$10$Nbl2b9wqd.rXqKEsd3pRSOoIyFAFIhbqf71BufwDfS3Guv21SlEx2" >>> $user->save(); => true >>> App\User::first()->toArray(); => [ "id" => "1", "name" => "zhang jinglin", "email" => "zjl@example.com", "created_at" => "2015-03-31 03:24:55", "updated_at" => "2015-03-31 03:24:55" ] >>>
现在我们需要新发布的文章和用户关联,我们暂时先修改 form_partial.blade.php 来隐藏一个用户id,只是暂时:
复制代码 代码如下:
{{--临时处理--}}
{!! Form::hidden('user_id', 1) !!}
同时要修改模型的 $fillabel 属性,以便我们的 Mass Assisment。
protected $fillable = [ 'title', 'body', 'published_at', 'user_id' //临时设置 ];
OK,添加一个文章。我们使用 tinker 来查看一下。
php artisan tinker Psy 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: "zjl@example.com", 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(); => <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: "zjl@example.com", created_at: "2015-03-31 03:24:55", updated_at: "2015-03-31 03:24:55" } >>>
相关推荐:
Laravel 关联模型由于名称一致性导致的问题 laravel 视频教程 thinkphp php laravel
laravel 学习笔记 —— 神奇的服务容器 laravel下载 yii php laravel
The above is the detailed content of Learn Laravel5's Eloquent relationship. For more information, please follow other related articles on the PHP Chinese website!

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
