我正在创建自己的项目管理器,目前有一个 projects
、users
和一个 project_users
表。我正在尝试在模型中创建关系以将一个项目与多个用户相关联,但我从未创建过多对多关系。我查看了文档并尝试了各种示例,但没有一个对我有用。
这是我的项目 Controller :
公共(public)函数 single( $id ) {
$project = Project::with('client','projecttypes','storys', 'sprints', 'projectusers')->find( $id )->toArray();
return View::make('projects.single', array( 'project' => $project ) );
}
这只是获取一个项目和所有相关模型并将它们返回到 View 。
我的项目模型:
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
除外。
我只需要弄清楚如何利用数据透视表将所有用户分配到特定项目,任何帮助将不胜感激!
谢谢
最佳答案
我在 Laravel 论坛上得到了答案,这里是:
项目 Controller
$project = Project::with('client','projecttypes','storys', 'sprints', 'users')->find( $id )->toArray();
项目
模型
public function users() {
return $this -> belongsToMany('User');
}
用户
模型
public function projects() {
return $this -> belongsToMany('User');
}
这对我有用!
关于mysql - 使用数据透视表的 Laravel Eloquent 多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26328839/