Laravel 5: Many-to-many, implementing articles and tags

Source: Internet
Author: User
Original from HTTPS://LARAVIST.COM/ARTICLE/18

Laravist is my just on-line laravel community, there are any issues related to Laravel can come here to ask me, I will try to help you solve the problem, later will try to record some video tutorials, the form is probably like this

Https://laravist.com/lesson/1

Prelude

Before starting the text, let's start by saying that in actual development, there are often several common correspondence patterns that are exposed:

One-to-one//one-to-one one-to-many//one-to-many many-to-many//many to many

I don't know how you feel about these concepts, if you don't understand them. You can apply these concepts to your life, and it's easy to understand, and give us an example of what we see on the Web:

User-to-profile//One-to-oneuser-to-articles//one-to-manyarticle-to-comments//one-to-manyarticles-to-tags// Many-to-many

The translation comes from:

One user profile for one user

One user can post multiple articles

A post can have multiple comments

While articles and tags are really many-to-many relationships, an article can have multiple tags; a label can belong to multiple articles

In these relational models, the most difficult to achieve is many-to-many this many-to-many relationship, but our simple blog does not have user management, that is, there is no open for users to register, so we still have to challenge the difficulty here, Realize articles-to-tags This many-to-many relationship, with the help of Laravel's powerful eloquent, realize this function is still more satisfactory. As for one-to-one and one-to-many relationships, you can comprehend by analogy.

Create tags table

To achieve articles-to-tags This many-to-many relationship, we need tags table and Tag model, so we create it separately.

PHP Artisan make:migration create_tags_table--create=tags

Open the generated migration file and add a line of code to the Up () method:

Public function up () {  schema::create (' tags ', function (Blueprint $table) {    $table->increments (' id ');    $table->string (' name ');    $table->timestamps ();  });}

Here we have added $table->string (' name '); In this line, this field represents the tag table by adding a Name field that represents the name of the label.

Next, we create a TAG model for the tags table:

PHP Artisan Make:model Tag

After generating the TAG model, we do not have to pipe the tag.php file, because we also need a relational table article_tag, this table only exists tag_id and article_id, so we create it:

PHP Artisan make:migration create_article_tag_table--create=article_tag

Open the migration file to add both the tag_id and article_id fields:

Public function up ()  {    schema::create (' Article_tag ', function (Blueprint $table) {      $table->increments (' id ');      $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 ();    });  }

This seems to add the two fields tag_id and article_id, but with a lot of line code, we just have to understand the following:

$table->foreign (' article_id ')->references (' id ')->on (' articles ')->ondelete (' cascade ');

Foreign (): foreign key

References (): Reference field

On (): Reference table

OnDelete (): Execution action on delete

This is followed by deletion, such as the deletion of an article, we will Article_tag contains article_id the same record also deleted

Finally, execute migration to generate the Article_tag table:

PHP Artisan Migrate

OK, after generating these two tables, we can formally start our work.

Declare the relationship of eloquent

Articles and tags are many-to-many relationships, so we need to declare the following relationship in article.php:

Public Function tags ()    {        return $this->belongstomany (' App\tag ');    }

In tag.php, too:

Public function articles ()    {        return $this->belongstomany (' app\article ');    }

We use the $this->belongstomany () to indicate the relationship between eloquent, it is important to note that if your foreign key is not article_id and tag_id, you need to set it in the third parameter, written like this:

Public function articles ()    {        return $this->belongstomany (' app\article ', ' conversation_id ');    }

OK, so that our many-to-many relationship is declared complete.

Using Select2

Before we start, we use Tinker to generate a few tags, the process does not demonstrate, and finally the following:

Then, for a better user experience, we introduced Select2, which was perfect for selecting multiple options.

Select2 Usage: https://select2.github.io/examples.html

We introduced Select2 CSS files and JS files in app.blade.php:

 
  

Within the tag, we also introduced jquery, because Select2 relies on jquery, so. Note the download or source of the file, please obtain it yourself.

After introduction, we can still use our form to create our selection box in the file creation page, come to the articles/create.blade.php file, add an input form below PUBLISHED_AT:

        {!! Form::label (' tag_list ', ' select Tag ')        !! {!! Form::select (' tag_list[] ', $tags, null,[' class ' = ' Form-control js-example-basic-multiple ', ' multiple ' = ' Multiple '])!

Note Here is tag_list[], if we just use tag_list, we can only choose a label, if we need to select more than one, we need to have an array of the form to store our labels, and one is to specify the ' multiple ' and ' Multiple ', is to turn on support multi-select mode. Then $tags is that we need to get the tags table from the database data, so naturally, we go to the Articlecontroller in the Create () method, slightly modify the code:

Public function Create ()    {        $tags = tag::lists (' name ', ' id ');        In order to display the label in the interface Name,id in order to save the article when used.        return view (' Articles.create ', compact (' tags '));    }

Here we use the lists () method to return the tag (for tags data table) name and ID in a eluqoent way, you can use DD ($tags) to see. Well, take a look at our create page this time:

At this point we found that the style is not Select2 so good, it is because we have not initialized Select2, so we write a few lines in create.blade.php JS code:

In the @endsection followed by the previous line with the above code, here we use jquery selector, and then call Select2 (); To initialize our selection box and then look at the effect:

It's perfect, we're going to make the whole UI perfect, we use DD (), to see what our form is submitting, and add a line of code to the store () method in Articlecontroller:

DD ($request->all ());

Let's look at the effect:

We see that the tag_list is an array, the value is not the name of the tag we choose, but the ID of the tag, so we can use the laravel provided by the Attach () to add our tag, this attach () accepts an array of IDs, this is exactly! , so let's change the store () method a little bit:

Public function Store (requests\storearticlerequest $request)  {    $input = $request->all ();    $input [' intro '] = Mb_substr ($request->get (' content '), 0,64);    $article = Article::create ($input);    $article->tags ()->attach ($request->input (' tag_list '));    Return redirect ('/');  }

Here we will first assign the Article::create ($input) $article variable (the eloquent object) and then use $article->tags ()->attach () to add the label and pass our label array to Attach () method, let's see if there is success:

Here's the article is published successfully, we come to see if our label is added successfully, to see our article_tag table:

is added three tags, but we found this created_at and Updated_at seems a bit of a problem, let's fix it, in article.php in the tags () method:

Public Function tags ()    {        return $this->belongstomany (' App\tag ')->withtimestamps ();    }

We use Withtimestamps () to synchronize our time in the back, and we'll try it again:

Take a look at our database:

It's perfect to see the last two records.

Show our tags in the view

Now that we have the label, why don't we show it? In articles/index.blade.php, let's export the label of the file:

ID}} "> {{$article->title}}

  • {{$article->published_at->diffforhumans ()}}}
  • @if ($article->tags) @foreach ($article->tags as $tag)
  • {{$tag->name}}
  • @endforeach @endif

We are

Add a

    list below the label, and then first publish the date Published_at output, here we use the Carbon Diffforhumans () method, this method will produce a few minutes ago, a few hours before the effect, here can also appreciate our The Published_at object needs to be treated as a carbon object before, and if it is simply a string, it is not possible to call Carbon's Diffforhumans () method.

    Next, we use the $article->tags to get the label of the article, which is our tags () method of declaring many-to-many relationships. Let's take a look at the effect:

    We found out how many minutes before we were in English, that's because we didn't set carbon, let's fix it, boot in app/providers/appserviceprovider.php The () method adds the following line:

    \carbon\carbon::setlocale (' zh '); 

    Then refresh and witness the miracle:

    Summary

    Here we use the Attach () method provided by Laravel to implement the basic many-to-many relationship, and also slightly beautify the output, will The Published_at field is rendered perfectly.

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.