首页 文章

Laravel 5数据透视表项目< - >用户

提问于
浏览
2

我发现数据透视表非常复杂,我不知道下一步该做什么或我做错了什么,我找到了一些教程,但没有帮助我满足我的需求 .

我有 projectsusersmany-to-many 关系 . 一个 project hasMany users 和一个 user hasMany projects .

我现在拥有的项目没有与用户的关系 .

这是我到目前为止:

Projects table

class CreateProjectsTable extends Migration {

public function up()
{
    Schema::create('projects', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('name');
        $table->date('completion_date');
        $table->integer('completed')->default(0);
        $table->integer('active')->default(0);
        $table->timestamps();
    });
}

Users table

class CreateUsersTable extends Migration {

public function up()
{
    Schema::create('users', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('company_id');
        $table->integer('project_id');
        $table->integer('usertype_id')->default(0);
        $table->string('username');
        $table->string('password');
    });
}

Project User table (pivot)

class CreateProjectUsersTable extends Migration {

public function up()
{
    Schema::create('project_users', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('project_id')->references('id')->on('project');;
        $table->integer('user_id')->references('id')->on('user');;
    });
}

User model

public function projects() {
    return $this->belongsToMany('App\Project', 'project_users', 'user_id', 'project_id');
}

Project model

public function users() {
    return $this->belongsToMany('App\User', 'project_users', 'project_id', 'user_id');
}

Project controller

public function index(Project $project)
{

   $projects = $project->with('users')->get();

    dd($projects);

    $currenttime = Carbon::now();

    //return view('project.index', array('projects' => $projects, 'currenttime' => $currenttime));

    return view('user.index', compact('projects'));
}

1 回答

  • 2

    User 模型中的关系不正确 . 你必须交换钥匙 .

    public function projects() {
        return $this->belongsToMany('App\Project', 'project_users', 'user_id', 'project_id');
    }
    

    Edit regarding latest comment:

    不要考虑数据透视表,只要你的关系设置正确,我相信它们是正确的,Laravel会为你处理所有这些 .

    现在 $projects->users 没有任何意义,因为 projects 没有 users . projects 只是 Project 的集合 . 该集合中的每个 Project 都将具有 users 关系 . 您必须遍历集合才能查看每个 Project 的用户 .

    foreach($projects as $project) {
        foreach($project->users as $user) {
            echo $user;
        }
    }
    

相关问题