D
D
Denis2021-03-04 11:07:36
Laravel
Denis, 2021-03-04 11:07:36

Can't figure out Laravel relationships?

I am going through php training, now we are writing a project on laravel and something is stuck on relationships. Can't figure out how it works? Already read the dock and third-party resources and that there is no complete picture yet.
The question is. There are 3 tables task, user, status. I need an association between task=user and task=status.
Task = Status I set up and then probably more by typing. Now this is how I get the status name $task->status->name
of the Task model

public function status()
    {
        return $this->belongsTo(TaskStatus::class);
    }

task migration
$table->id();
            $table->string('name');
            $table->string('description')->nullable();
            $table->integer('status_id')->default(1);
            $table->integer('created_by_id');
            $table->timestamps();

status model
public function task()
    {
        return $this->hasMany(Task::class, 'status_id');
    }

status migration
$table->id();
            $table->string('name');
            $table->timestamps();

everything works, in a similar way $task->status->name I get the status

by analogy, I try to get the name of the user who created the task
model Task
public function user()
    {
        return $this->belongsTo(User::class);
    }

user model
public function tasks()
    {
        return $this->hasMany(Task::class, 'created_by_id');
    }

but when trying to get the name $task->user->name comes null. And I don't understand why. Everything seems to be the same as in the first case ... in short, stuck. I tried to link tables through foreign, but there I threw errors during migration ...
At the same time, I’ll sit down myself and look at what I wrote, sometimes you write a question and then you find the answer yourself .... well, or who will tell you where to dig to figure it out ....

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2021-03-04
@jazzus

$table->integer('created_by_id');
replaced by

$table->foreignId('user_id')->constrained('users');

only the id field in the users table should be
$table->id();
i.e. bigIncrements

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question