Answer the question
In order to leave comments, you need to log in
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();
});
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();
});
Answer the question
In order to leave comments, you need to log in
$table->foreign('author_id')->references('id')->on('users');
In the User.php model write:
public function posts() {
return $this->hasMany('App\Post', 'author_id');
}
public function user() {
return $this->belongsTo('App\User', 'author_id');
}
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');
}
public function posts()
{
return $this->hasMany('App\Models\Post', 'user_id');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question