【问题标题】:Laravel 'many to many' user associates with many posts?Laravel“多对多”用户关联很多帖子?
【发布时间】:2018-07-26 22:49:07
【问题描述】:

在 PostsController 中

public function store()
    {
        $this->validate(request(), [
            'title' => 'required',
            'body' => 'required'
        ]);

        auth()->user()->publish(
            new Post(request(['title', 'body']))
        );

        return redirect('/');
    }

在user.php中

 public function posts()
    {
        return $this->belongsToMany(Post::class);
    }

    public function publish(Post $post)
    {
        $this->posts()->save($post);
    }

问题是登录后我看到所有帖子仅与登录用户相关联,但我想要许多帖子与许多用户关系

【问题讨论】:

    标签: laravel foreign-keys posts


    【解决方案1】:

    用户模型一定是这样的

    class User extends Authenticatable
    {
           public function Posts()
           {
               return $this->belongsToMany('App\Post');
           }
    }
    

    post模型一定是这样的。

    class Post extends Model
    {
    
            public function users()
            {
                return $this->belongsToMany('App\User');
            }
    }
    

    用户的迁移类

    class CreateUsersTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
           Schema::create('users', function (Blueprint $table) {
                      $table->increments('id');
                      $table->string('name');
                      $table->string('email')->unique();
                      $table->string('password');
                      $table->rememberToken();
                      $table->timestamps();
                  });
        }
    
       /**
            * Reverse the migrations.
            *
            * @return void
            */
           public function down()
           {
               Schema::dropIfExists('users');
           }
    }
    

    Post 的迁移类

    class CreatePostsTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
             Schema::create('posts', function (Blueprint $table) {
                $table->increments('id');
                $table->string('title');
                $table->text('body');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('posts');
        }
    }
    

    你还需要一个数据透视表。表名必须是-user_post

    class CreatePostUser extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         * user_post
         */
        public function up()
        {
            Schema::create('post_user', function(Blueprint $table)
            {
                      $table->integer('user_id')->unsigned()->nullable();
                                $table->foreign('user_id')->references('id')
                                    ->on('users')->onDelete('cascade');
    
                                $table->integer('post_id')->unsigned()->nullable();
                                $table->foreign('post_id')->references('id')
                                    ->on('posts')->onDelete('cascade');
    
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('user_post');
        }
    }
    

    更多详情请参考此链接 - https://laravel.com/docs/5.5/eloquent-relationships#many-to-many

    我希望你觉得这很有用!

    【讨论】:

    • 看到这个错误 SQLSTATE[42S02]: Base table or view not found: 1146 Table 'logos.post_user' 不存在(SQL: insert into post_user (post_id, user_id ) 值 (1, 1))
    • 你能发布你的代码吗?我想看看,你是如何保存数据的。
    • 在 User.php public function publish(Post $post) { $this->posts()->save($post); } 在 PostController public function store() { $this->validate(request(), [ 'title' => 'required', 'body' => 'required' ]); auth()->user()->publish( new Post(request(['title', 'body'])) ); return redirect('/'); }
    • 哦.. 抱歉,在这种情况下,您能否将数据透视表名称更改为 post_user。表名必须是 - post_user。
    • 添加后我已经添加了 user_post 我看到了这个错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 2018-06-28
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 2022-01-23
    • 2017-04-16
    相关资源
    最近更新 更多