search
HomePHP FrameworkLaravelA brief analysis of Many-To-Many in Laravel

In actual development, we often come into contact with several common correspondence patterns:

One-To-One //一对一

One-To-Many //一对多

Many-To-Many //多对多

When I first came into contact with these concepts, I actually didn’t quite understand them. But once you apply these concepts to life, it's easy to understand. Let's take an example that we often see online:

User-To-Profile // One-To-One

User-To-Articles // One-To-Many

Articles-To-Tags // Many-To-Many

translates to:

  1. One user corresponds to one user profile
  2. A user can publish multiple articles
  3. There is a many-to-many relationship between articles and tags. An article can have multiple tags; a tag can belong to Multiple articles

Among these relationship models, the most difficult to implement is the many-to-many relationship Many-To-Many, but with the help of Laravel’s powerful Eloquent, it is quite satisfying to implement this function.

1. Create database table

Createarticlestable

Schema::create('articles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('content');
            $table->timestamps();
        });

Createtagstable

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

Of course , to solve this classic problem, these two tables alone are not enough. It is necessary to establish a relationship table in addition to these two tables to connect article and tag. In Laravel, if you follow the official standard rules, the third table should look like this:

Table namearticle_tag

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

If you do not follow the official specifications Now, you need to specify the foreign key in the model.

2. Create the model and specify the relationship

In Article.php:

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

In Tag.php:

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

Note two points here:

  1. You can specify foreign keys when declaring the relationship, such as $this->belongsToMany('App\Article',' foreign_key', 'other_key');
  2. If you add timestamps() in the article_tag table, that is, the two fields created_at and updated_at appear in the table, you need to do this when declaring the relationship in Article :return $this->belongsToMany('App\Tag')->withTimestamps();
##3. Use# in

Controller ## If we want to check which tags an article contains, we can do this:

$article = Article::find($id);

dd($article->tags);

If we want to find an article by a certain tag:

<code><br>public function showArticleByTagName($name)
    {
        $tag = Tag::where('value','=',$name)->first();

        dd($tag->articles);
    }</code>

The above is achieved.

Many-To-Many

. in Laravel

The above is the detailed content of A brief analysis of Many-To-Many in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Last Laravel version: Migration TutorialLast Laravel version: Migration TutorialMay 14, 2025 am 12:17 AM

What new features and best practices does Laravel's migration system offer in the latest version? 1. Added nullableMorphs() for polymorphic relationships. 2. The after() method is introduced to specify the column order. 3. Emphasize handling of foreign key constraints to avoid orphaned records. 4. It is recommended to optimize performance, such as adding indexes appropriately. 5. Advocate the idempotence of migration and the use of descriptive names.

What is the Latest LTS Version of Laravel?What is the Latest LTS Version of Laravel?May 14, 2025 am 12:14 AM

Laravel10,releasedinFebruary2023,isthelatestLTSversion,supportedforthreeyears.ItrequiresPHP8.1 ,enhancesLaravelPennantforfeatureflags,improveserrorhandling,refinesdocumentation,andoptimizesperformance,particularlyinEloquentORM.

Stay Updated: The Newest Features in the Latest Laravel VersionStay Updated: The Newest Features in the Latest Laravel VersionMay 14, 2025 am 12:10 AM

Laravel's latest version introduces multiple new features: 1. LaravelPennant is used to manage function flags, allowing new features to be released in stages; 2. LaravelReverb simplifies the implementation of real-time functions, such as real-time comments; 3. LaravelVite accelerates the front-end construction process; 4. The new model factory system enhances the creation of test data; 5. Improves the error handling mechanism and provides more flexible error page customization options.

Implementing Soft Delete in Laravel: A Step-by-Step TutorialImplementing Soft Delete in Laravel: A Step-by-Step TutorialMay 14, 2025 am 12:02 AM

Softleteinelelavelisling -Memptry-braceChortsDevetus -TeedeecetovedinglyDeveledTeecetteecedelave

Current Laravel Version: Check the Latest Release and UpdatesCurrent Laravel Version: Check the Latest Release and UpdatesMay 14, 2025 am 12:01 AM

Laravel10.xisthecurrentversion,offeringnewfeatureslikeenumsupportinEloquentmodelsandimprovedroutemodelbindingwithenums.Theseupdatesenhancecodereadabilityandsecurity,butrequirecarefulplanningandincrementalimplementationforasuccessfulupgrade.

How to Use Laravel Migrations: A Step-by-Step TutorialHow to Use Laravel Migrations: A Step-by-Step TutorialMay 13, 2025 am 12:15 AM

LaravelmigrationsstreamlinedatabasemanagementbyallowingschemachangestobedefinedinPHPcode,whichcanbeversion-controlledandshared.Here'showtousethem:1)Createmigrationclassestodefineoperationslikecreatingormodifyingtables.2)Usethe'phpartisanmigrate'comma

Finding the Latest Laravel Version: A Quick and Easy GuideFinding the Latest Laravel Version: A Quick and Easy GuideMay 13, 2025 am 12:13 AM

To find the latest version of Laravel, you can visit the official website laravel.com and click the "Docs" button in the upper right corner, or use the Composer command "composershowlaravel/framework|grepversions". Staying updated can help improve project security and performance, but the impact on existing projects needs to be considered.

Staying Updated with Laravel: Benefits of Using the Latest VersionStaying Updated with Laravel: Benefits of Using the Latest VersionMay 13, 2025 am 12:08 AM

YoushouldupdatetothelatestLaravelversionforperformanceimprovements,enhancedsecurity,newfeatures,bettercommunitysupport,andlong-termmaintenance.1)Performance:Laravel9'sEloquentORMoptimizationsenhanceapplicationspeed.2)Security:Laravel8introducedbetter

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 Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

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),