mercredi 5 décembre 2018

Laravel 5 - Defining Two Relationships Between Models

I'm learning Laravel, and really OOP in general. I've followed several YouTube tutorial series, that teach you to create a blog in Laravel.

I'm building a task app for a brewery, and I'm trying to define the relationships between the users and the tasks. So I have two models: User.php and Task.php. I had no problem defining the user in a hasMany tasks relationship, and reciprocally, a task belongsTo a user. Where I'm confused is that I'd like to also have a user belong to the task as well. I have two MySQL columns, one with the heading of "user_id" and the other with "user_assigned_id". What I want is that a user has many tasks, but a task also has one assigned user, the idea being that the user that created the task might assign the task to another user. I've found several tutorials on creating relationships between three models, such as a user owning several messages, but only having one address, so I figured that I could just treat two models as if they were three models and connected the User model back to the Task model in a hasOne relationship, but I'm having a really hard time passing that through to the Controller and View.

Here is the relevant code in each file:

User.php

public function tasks()
{
    return $this->hasMany('App\Task');
}

Task.php

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

//  Added an user_assigned_id relationship
public function user_assigned()
{
    return $this->hasOne('App\User', 'name', 'user_assigned_id');
}

DashboardController.php

public function index()
{
    $user_id = auth()->user()->id;
    $now = Carbon::now();

    $tasks_assigned = Task::orderBy('date', 'asc')->whereDate('date', '>=', $now)->where('user_assigned_id', '=', $user_id)->user_assigned()->where('name', '=', 1)->get();

    $tasks_created = Task::orderBy('date', 'asc')->whereDate('date', '>=', $now)->where('user_id', '=', $user_id)->get();

    return view('dashboard')->with('tasks_assigned', $tasks_assigned)->with('tasks_created', $tasks_created);
}

I've gotten a bit turned around in the Controller, so I'm not sure if I messed something up there. Basically, I'm getting results from tasks owned by the logged in user, but not assigned to the logged in user.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2RIyRRG
via IFTTT

Aucun commentaire:

Enregistrer un commentaire