W
W
WQP2016-12-28 13:35:50
Laravel
WQP, 2016-12-28 13:35:50

How to make laravel table link?

Hello, just learning laravel and trying to build a small blog. I was looking for how to make a connection between tables and did not find it.
There is a standard user migration:

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

And migration for posts:
Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('slug')->unique();
            $table->string('title');
            $table->string('thumb');
            $table->text('content');
            $table->integer('author_id');
            $table->timestamps();
            $table->timestamp('published_at')->index();
        });

How do I associate user ID with author_id?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
Ramm, 2016-12-28
@WQP

$table->foreign('author_id')->references('id')->on('users');

https://laravel.com/docs/5.3/migrations#indexes

Z
Zlatoslav Desyatnikov, 2016-12-28
@pxz

https://laravel.ru/docs/v5/eloquent-relationships

V
Vlad, 2016-12-28
@Result007

In the User.php model write:

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

And in Post.php
public function user() {
    return $this->belongsTo('App\User', 'author_id');
}

V
Vasyl Fomin, 2016-12-28
@fomvasss

It is well described here https://laravel-news.ru/blog/tutorials/eloquent-re...
In the posts table, you need to create a field not author_id but user_id , then laravel will automatically "know" through which field all this needs to be knitted.
I did like this:
- in post table migration:
...
- in post model:

public function user()
    {
        return $this->belongsTo('App\Models\User', 'user_id');
    }

- in the user model:
public function posts()
    {
        return $this->hasMany('App\Models\Post', 'user_id');
    }

Of course, it is not necessary to specify the user_id foreign key in models if you have field names set according to laravel rules

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question