Have you watched any laracast on relations or dug into the documentation on one to many and many to many and really all types of relations? Jeffrey includes some examples in the docs and there is also tutorials included in the docs.
Get information from 3 diffrent tables to one page
Hello Laracasters!
This is a follow up on my previous question, which seemed like noone had a answer to unfortunately (https://laracasts.com/discuss/channels/code-review/only-gets-the-correct-name-and-id) I will instead try to explain what i want to achieve with out the code.
I have a users table
- ID
- Name
- Number
- Password
- Rember_Token
Tasks Table:
- ID
- Title
- Description
- fk_user_id_assign
- fk_user_id_created
- fk_client_id
And then the clients table:
- ID
- Name
- Number
- fk_user_id
On the clients Show page, i wanna display the tasks the client currently have, in a list with the title, but here comes what i can't get working, besides the title i want what user is assigned to the Task aswell. How can i achieve this?
So Clients profile page > List of tasks with Users assigned to the task, and the email and number of the user(Not client)
If you can use the convention for ids and foreign keys then it will save further hassle
No need to use has manyThrough since most times you will want all tables anyway.
So you have
- client that has many tasks
- task that belongs to a client
- task that belongs to a user
- user that has many tasks assigned
- user that has many tasks created
in your Client model
protected $primaryKey ='ID';
public function tasks()
{
return $this->hasMany('App\Task);
}
in your Task model
protected $primaryKey ='ID';
public function client()
{
return $this->belongsTo('app\Client','fk_client_id');
}
public function taskCreator()
{
return $this->belongsTo('app\User','fk_user_id_created');
}
public function taskAssignedTo()
{
return $this->belongsTo('app\User','fk_user_id_assign');
}
in your User model
protected $primaryKey ='ID';
public function tasksAssigned()
{
return $this->hasMany('app\Task','fk_user_id_assign');
}
public function tasksCreated()
{
return $this->hasMany('app\Task','fk_user_id_created');
}
.... or something like that..
then to get the data for your page, you will be able to eager load the relationships, like
$client = Client::with('tasks','task.assignedTo')->findOrFail(1);
return view('clientTasks')->with(compact('client'));
and in your view you will have a client object with a collection of client tasks, and each task will have a child element of the user assigned.
@foreach($client->tasks as $task)
<td>{{ $task->Title}}</td>
<td{{ $task->user->Name }}</td>
@endforeach
Please or to participate in this conversation.