E
E
E6APB2017-07-26 15:30:13
MySQL
E6APB, 2017-07-26 15:30:13

How to connect correctly 2 models in this case?

There is a Task model. The structure in the database is:

tasks
    id
    user_id
    task_type_id
    data

And there is a TaskType model
task_types
    id
    service_id
    name

I have one task can have only one TaskType. But one TaskType can have many tasks. I can't find the right relationship. For one-to-one, the TaskType needs to have a task_id field, which I don't need. TaskType - a kind of reference book of possible types of tasks. How can I link them?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pushkarev, 2017-07-26
@E6APB

Something like this

class TaskType extends Model
{
    public function tasks()
    {
        return $this->hasMany('App\Models\Task');
    }
}

class Task extends Model
{
    public function type() {
        return $this->belongsTo('App\Models\TaskType');
    }
}

change the namespace to your own. In general, it is better to do them as I showed. It is not very convenient to store them in the app folder

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question