【发布时间】:2014-12-07 08:38:07
【问题描述】:
我正在创建自己的项目经理,我目前有一个projects、users 和一个project_users 表。我正在尝试在模型中创建关系以将一个项目与多个用户相关联,但我从未创建过多对多关系。我查看了文档并尝试了各种示例,但没有一个对我有用。
这是我的项目控制器:
公共函数单($id){
$project = Project::with('client','projecttypes','storys', 'sprints', 'projectusers')->find( $id )->toArray();
return View::make('projects.single', array( 'project' => $project ) );
}
这只是抓取单个项目和所有相关模型并将它们返回到视图中。
我的项目模型:
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' );
}
}
我的用户模型:
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');
}
}
最后是我的 ProjectUsers 模型:
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');
}
}
数据库中的所有字段都列在模型 $fillable 中,但主 ID id 除外。
我只需要弄清楚如何使用数据透视表将所有用户分配到特定项目,我们将不胜感激!
谢谢
【问题讨论】:
标签: mysql database laravel-4 many-to-many eloquent