zoukankan      html  css  js  c++  java
  • laravel实现多对多的分析

    在实际开发中多对多的开发还是比较常见的

    1.1首先由migrate来创建表(文章表)

    1.2同理创建标签表

    1.3这是 我会的到如下结果:

    2.1在数据迁移表contents中添加几个字段

     public function up()
        {
            Schema::create('contents', function (Blueprint $table) {
                $table->increments('id');
    
                $table->string('title');
                $table->text('body');
    
                $table->timestamps();
            });
        }

     2.2在数据迁移表tag中添加如下字段:

    public function up()
        {
            Schema::create('tags', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->timestamps();
            });
    
            Schema::create('content_tag', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->integer('content_id')->unsigned()->index();
                $table->integer('tag_id')->unsigned()->index();
    
                //设置外键
                $table->foreign('content_id')->references('id')->on('contents')->onDelete('cascade');
                $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
                $table->timestamps();
            });
        }

    3.3这时运行如下的artisan命令

    php artisan migrate

     在数据库表中可以看到如下表

    这时就在两个模型中各添加一个方法 

     //在Content模型中 添加
    
     public function tags()
        {
            return $this->belongsToMany(Tag::class);
        }
    
    //在Tag模型中 添加
    public function contents()
        {
            return $this->belongsToMany(Content::class);
        }

    现在进入测试阶段代码如下

    //向各表中添加20条数据
    
    factory(Content::class,20)->create();
    
    factory(Tag::class,20)->create();

    结果如下:

    最后几步配置路由如下

    Route::get('/', function () {
         $content = AppContent::find(3);
       //在content_tag表中添加tag标签为3和content表中id为3的数据
         $content_tag = $content->tags()->attach(3);
    
        //进行删除数据
        // $content_tag = $content->tags()->detach(3);
         dd($content_tag);
        return view('welcome');
    });

    紧接着启动服务器 

    php artisan  serve

     测试结果:在表中的数据

     

    删除之后的结果

     

  • 相关阅读:
    程序集、属性和元数据
    wget 使用探索
    为wget使用代理
    创建项目 (Visual C#)
    wget 下载整个网站,或者特定目录
    演练:使用 Visual C# 创作用户控件
    NavigateUrl属性绑定 天高地厚
    【转载】Repeater控件里的大智慧 天高地厚
    【转载】ASP.NET Page 那点事 天高地厚
    意向锁如何提高性能 天高地厚
  • 原文地址:https://www.cnblogs.com/webph/p/6424240.html
Copyright © 2011-2022 走看看