Laravel5 series Tutorial 9: EloquentRelationship

Source: Internet
Author: User
Laravel5 series Tutorial 9: EloquentRelationship

From https://laravist.com/article/18

Laravist is the Laravel community I just launched. if you have any questions related to Laravel, please come here and ask me. I will try my best to solve the problem. later I will try to record some video tutorials, this is probably the form

Https://laravist.com/lesson/1

Prelude

Before starting the text, we will first talk about several common ing modes in actual development:

One-To-One // One-To-Many // One-To-Multiple-To-Many // multiple-To-Many

I don't know how you feel about these concepts. You can apply these concepts to your life and understand them very easily. here is an example we often see on the Internet:

User-To-Profile // One-To-OneUser-To-Articles // One-To-ManyArticle-To-Comments // One-To-ManyArticles-To-Tags // Many-To-Many

The translation is:

  • A user corresponds to a user file

  • One user can post multiple articles

  • One article can have multiple comments

  • The relationship between articles and tags is indeed many-to-many. one article can have multiple tags, and one tag can belong to multiple articles.

  • Among these relational models, the most difficult thing To implement is the Many-To-Many relationship, but we have no user management for this simple blog, that is To say, it is not open for user registration, so here we still need To challenge the difficulty To implement the article-To-Tags relationship, with the powerful Eloquent of Laravel, it is quite easy to implement this function. The one-to-one and one-to-many relationships can be bypassed.

    Create a tags table

    We need To create the Tags table and Tag model To implement the rule-To-pair relationship such as Articles-To-tags.

    php artisan make:migration create_tags_table --create=tags

    Open the generated migration file and add a line of code for the up () method:

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

    The $ table-> string ('name'); line is added. This field adds a name field to the tags table, representing the name of the tag.

    Next, we will create a Tag model for the tags table:

    php artisan make:model Tag

    After the Tag model is generated, we do not need to worry about the Tag. php file, because we also need a relational table article_tag, which only stores tag_id and article_id, so we will create it:

    php artisan make:migration create_article_tag_table --create=article_tag

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

     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();        });    }

    The tag_id and article_id fields seem to be added here, but many lines of code are used, as long as we understand the following:

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

    Foreign (): foreign key
    References (): reference field
    On (): reference table
    OnDelete (): The action executed during deletion.
    This is followed by deletion. for example, if an article is deleted, we will delete records with the same article_tag as article_id.

    Finally, execute migration to generate the article_tag table:

    php artisan migrate

    OK. after the two tables are generated, we can start our work.

    Declare the relationship of Eloquent

    The relationship between Articles and Tags is many-to-many, so we need to declare the following relationship in Article. php:

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

    In Tag. php, the same is true:

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

    We use $ this-> belongstoent () to indicate the relationship between Eloquent. Note that if your foreign key is not article_id or tag_id, you need to set it in the third parameter, it is written as follows:

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

    OK. in this way, the multi-to-many relationship is declared.

    Use Select2

    Before we start, we use tinker to generate several tags, and the process will not be demonstrated. Finally, it is like this:

    Then, we introduce Select2 for better user experience, which performs exceptionally well when multiple options are selected.

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

    We introduced Select2 css files and js files in app. blade. php:

     

    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.