artisticre
2 months ago
186
1
Laravel

DB Question

Posted 2 months ago by artisticre

I have two tables Users and Posts. I am trying to understand relationships. I have already created these tables and everything is working. Now I want to create a controller that lists the posts based on the user_id. Would I put a column in the Posts table called user_id to be able to query the db or is there a better way?

User Model

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

Post Model

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

Users Table

 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

Posts Table

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

Please sign in or create an account to participate in this conversation.