I'm working on creating my own Project Manager, I currently have a projects
, users
and a project_users
table. I am trying to create the relationships in the models to associate one project to many users, but I have never created a many to many relationship. I looked at the documentation and tried various examples but none worked for me.
Here is my ProjectController:
public function single( $id ) {
$project = Project::with('client','projecttypes','storys', 'sprints', 'projectusers')->find( $id )->toArray();
return View::make('projects.single', array( 'project' => $project ) );
}
This is simply grabbing a single project and all of the related models and returning them to the view.
My Project model:
class Project extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'projects';
protected $fillable = array( 'client_id', 'title', 'description', 'type_id', 'status', 'hours_estimated', 'hours_actual', 'date_estimated', 'date_due', 'date_completed', 'created_at', 'updated_at' );
public function projectusers() {
return $this -> hasMany( 'User', 'id', 'user_id' );
}
}
My users model:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array( 'password', 'remember_token' );
protected $fillable = array( 'client_id', 'title', 'first_name', 'last_name', 'address', 'city', 'state', 'zip', 'email', 'password', 'status', 'created_at', 'updated_at', 'remember_token', '_token' );
public function project() {
return $this -> belongsToMany('Project');
}
}
and finally my ProjectUsers model:
class ProjectUsers extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'project_users';
protected $fillable = array( 'project_id', 'assigner_id', 'user_id', 'notifications', 'created_at', 'updated_at' );
public function project() {
$this -> belongsTo('Project');
}
}
All fields in the database are listed in the models $fillable
with the exception of the primary id id
.
I just need to figure out how to get all users assigned to a specific project utilizing the pivot table, any help would be greatly appreciated!
Thanks
I got an answer on a Laravel Forum, here it is:
ProjectController
$project = Project::with('client','projecttypes','storys', 'sprints', 'users')->find( $id )->toArray();
Project
model
public function users() {
return $this -> belongsToMany('User');
}
User
model
public function projects() {
return $this -> belongsToMany('User');
}
This worked for me!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments