[Laravel5Fundamentals] 21-Many-to-ManyRelationshipsandTags

Source: Internet
Author: User
[Laravel5Fundamentals] 21-Many-to-ManyRelationshipsandTags tag examples of many-to-many relations

Preface

In the previous section, we will explain how to use the flash message to understand what flash message is and how to use it easily. In this section, we will explain the many-to-many forms of databases using the tags document as an example.

Description

Development Environment: Windows 7

Laravel version: 5 +

IDE: Phpstorm

Before the database, we introduced the Eloquent and Migration of Laravel and described the foreign key relationship between data tables in Relationships, which is also a basic one-to-many relationship.

In this section, we will explain many-to-many operations in the database, and the example is tags, the article tag.

Introduction of tags

Now the basic functions of our blog are available, such as writing articles and publishing articles. However, as there are more and more articles, the screening and management of articles becomes a problem. if you can tag the keywords of each article, the management of the article will be greatly improved.

Next, let's take a look at how Eloquent achieves tagging for the article.

When I opened Article. php, do you still remember the method in which we joined the author (User) for each Article? Even if you cannot answer this question, you can write a belonsto statement in the bottom user () method to indicate the article. This statement is opposite to hassag. only one author of belonsto can be used in this article. However, one author can use hassag for this relationship.

However, in tag, belonsto and haswon won't be able to communicate with each other. an article cannot only include belonsto and one tag. it should be belongsToMany tags.

Price another tags () method under the user () method, as shown below:

public function tags(){  return $this->belongsToMany('App\Tag');} 

Next, let's create a Tag Eloquent model.

Create a Tag model class and Tag table

Enter the command: php artisan make: model Tag in the command line.

Run the following command on the command line: php artisan make: migration create tagtable-create = tags.

Open create tagtable. php and create some attributes or columns of the tag table here:

public function up(){    Schema::create('tags', function (Blueprint $table) {        $table->increments('id');        $table->string('name');        $table->timestamps();    });    Schema::create('article_tag',function(Blueprint $table){        $table->integer('article_id')->unsigned()->index();        $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');        $table->integer('tag_id')->unsigned()->index();        $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');        $table->timestamps();    });}public function down(){    Schema::drop('tags');    Schema::drop('article_tag');} 

The reason for creating an external table (the "article_tag" table) at the same time is to associate the article and tag in a table to facilitate query.

Next, execute migration and execute: php artisan migrate in the command line.

Next, open Tag. php and create it.

Since the relationship between tag and Article is many-to-many, there should also be a method pointing to article in the Tag model class:

public function articles(){     return $this->belongsToMany('App\Article');                        |} 

After saving, open the command line and use tinker to verify the success: php artisan tinker

>>> $tag = new App\Tag;=> App\Tag {#646}>>> $tag->name='personal';=> "personal">>> $tag->save();=> true>>> App\Tag::all()->toArray();=> [    [      "id" => 1,      "name" => "personal",      "created_at" => "2016-04-30 13:48:49",      "updated_at" => "2016-04-30 13:48:49",    ],  ] 

Associate article and tag

Next we try to associate these two tables.

In tinker mode:

>>> App \ Tag: all ()-> toArray () ;=> [["id" => 1, "name" => "personal ", "created_at" => "13:48:49", "updated_at" => "13:48:49",],] >>>> $ article = App \ Article: first (); => App \ Article {#659 id: "1", user_id: "1", created_at: "15:05:18", updated_at: "15:05:18", title: "Tan Xiaolong's article", body: "true", published_at: "00:00:00", >>>> $ article-> toArray (); => ["id" => 1, "user_id" => "1", "created_at" => "15:05:18", "updated_at" => "15:05:18 ", "title" => "Tan Xiaolong's article", "body" => "true", "published_at" => "00:00:00",]> $ article-> tags ()-> attach (1); Illuminate \ Database \ QueryExceptionwithmessage 'sqlstate [23000]: Integrity constraint violation: 19 not null constraint failed: article_tag.created_at (SQL: insert into "article_tag" ("article_id", "tag_id") values (1, 1 ))'

Here, $ article-> tags ()-> attach (1) means to bind the tag id = 1 (attach) to this article through the tags () method.

Unfortunately, we reported an error because there was no creation time. Change it.

Open Article. php, find the tags () method, and modify it as follows:

public function tags(){    return $this->belongsToMany('App\Tag')->withTimestamps();} 

That's it.

Then execute the attach command:

>>>$ Article = App \ Article: first () ;=> App \ Article {#655 id: "1", user_id: "1", created_at: "15:05:18", updated_at: "15:05:18", title: "The article created by Tan Xiaolong", body: "true", published_at: "00:00:00", >>> $ article-> tags ()-> attach (1); => null> DB: select ('select * from article_tag '); => [{#650 + "article_id": "1", + "tag_id": "1", + "created_at": "14:00:31", + "updated_at ": "14:00:31" ,},] >>>$ article-> tags-> toArray (); => [["id" => 1, "name" => "personal", "created_at" => "13:48:49", "updated_at" => "13:48:49 ", "identifier" => ["article_id" => "1", "tag_id" => "1", "created_at" => "14:00:31 ", "updated_at" => "14:00:31",] >>>> $ article-> toArray () ;=> ["id" => 1, "user_id" => "1", "created_at" => "15:05:18", "updated_at" => "15:05:18 ", "title" => "Tan Xiaolong's article", "body" => "true", "published_at" => "00:00:00 ", "tags" => [["id" => 1, "name" => "personal", "created_at" => "13:48:49 ", "updated_at" => "13:48:49", "comment" => ["article_id" => "1", "tag_id" => "1 ", "created_at" => "14:00:31", "updated_at" => "14:00:31",],] >>> $ article-> tags-> lists ('name'); => Illuminate \ Support \ Collection {#653 all: ["personal",],}

After associating the article, we will associate the article with the tag:

>>>$ Tag = App \ Tag: first () ;=> App \ Tag {#666 id: "1", name: "personal", created_at: "13:48:49", updated_at: "13:48:49", >>>>$ tag-> articles-> toArray () ;=> [["id" => 1, "user_id" => "1", "created_at" => "15:05:18", "updated_at" => "15:05:18 ", "title" => "Tan Xiaolong's article", "body" => "true", "published_at" => "00:00:00 ", "identifier" => ["tag_id" => "1", "article_id" => "1",]

Haha, the tag and the one you automatically bound to the article directly come to reality.

Summary

This is what we will talk about today. it is equivalent to the expansion and application of Relationship.

I hope you can absorb and digest today's content. Mutual encouragement.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.